0
0
JUnittesting~15 mins

assertDoesNotThrow in JUnit - Build an Automation Script

Choose your learning style9 modes available
Verify that a method does not throw any exception
Preconditions (2)
Step 1: Call the 'calculate' method with inputs 10 and 2
Step 2: Verify that no exception is thrown during the method call
✅ Expected Result: The 'calculate' method completes without throwing any exception
Automation Requirements - JUnit 5
Assertions Needed:
Use assertDoesNotThrow to verify no exception is thrown when calling calculate(10, 2)
Best Practices:
Use lambda expression inside assertDoesNotThrow for the method call
Keep test method names descriptive and clear
Avoid catching exceptions manually inside the test
Automated Solution
JUnit
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import org.junit.jupiter.api.Test;

public class CalculatorTest {

    // Method to test
    public int calculate(int a, int b) {
        return a / b;
    }

    @Test
    public void testCalculateDoesNotThrow() {
        assertDoesNotThrow(() -> {
            int result = calculate(10, 2);
        });
    }
}

This test class defines a method calculate that divides two integers.

The test method testCalculateDoesNotThrow uses assertDoesNotThrow from JUnit 5 to check that calling calculate(10, 2) does not throw any exception.

The method call is wrapped inside a lambda expression passed to assertDoesNotThrow. This is the recommended way to verify that no exception occurs during execution.

We do not catch exceptions manually because assertDoesNotThrow handles that and fails the test if an exception is thrown.

Common Mistakes - 3 Pitfalls
Catching exceptions manually inside the test instead of using assertDoesNotThrow
Passing the method call result directly to assertDoesNotThrow instead of a lambda
Using assertDoesNotThrow for methods that should throw exceptions
Bonus Challenge

Now add data-driven testing with 3 different input pairs to verify calculate does not throw exceptions

Show Hint