Verify that a method does not throw any exception
Preconditions (2)
✅ Expected Result: The 'calculate' method completes without throwing any exception
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.
Now add data-driven testing with 3 different input pairs to verify calculate does not throw exceptions
assertDoesNotThrow in JUnit testing?assertDoesNotThrow in JUnit 5?assertDoesNotThrow(() -> { int x = 5 / 1; });assertDoesNotThrow:assertDoesNotThrow(() -> { int y = 10 / 0; });processData() that may throw a checked exception. How do you use assertDoesNotThrow to verify it runs without exceptions?Pass the test and this pattern moves unknown