How to Use assertDoesNotThrow in JUnit for Exception Testing
Use
assertDoesNotThrow in JUnit to check that a block of code runs without throwing any exceptions. It takes a Executable lambda and passes the test if no exception occurs, otherwise it fails.Syntax
The assertDoesNotThrow method takes a single argument: an Executable functional interface, usually provided as a lambda expression. It runs the code inside the lambda and passes the test if no exception is thrown.
Optional: You can also provide a custom failure message as the first argument.
java
assertDoesNotThrow(() -> {
// code that should not throw an exception
});Example
This example shows how to use assertDoesNotThrow to verify that a method runs without throwing exceptions.
java
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import org.junit.jupiter.api.Test; public class ExampleTest { void methodThatDoesNotThrow() { // This method does nothing that throws } @Test void testNoExceptionThrown() { assertDoesNotThrow(() -> methodThatDoesNotThrow()); } }
Output
Test passed
Common Pitfalls
- Passing code that actually throws an exception will cause the test to fail.
- Do not confuse
assertDoesNotThrowwithassertThrows, which expects an exception. - Make sure the lambda does not swallow exceptions silently; the test only passes if no exception escapes.
java
/* Wrong: This test will fail because exception is thrown */ // assertDoesNotThrow(() -> { throw new RuntimeException("fail"); }); /* Right: No exception thrown */ // assertDoesNotThrow(() -> System.out.println("No error"));
Quick Reference
| Usage | Description |
|---|---|
| assertDoesNotThrow(() -> code) | Passes if code runs without exceptions |
| assertDoesNotThrow(() -> code, "message") | Fails with message if exception thrown |
| Use with lambdas or method references | Clean and readable test code |
Key Takeaways
Use assertDoesNotThrow to verify code runs without exceptions in JUnit tests.
Pass the code to test as a lambda expression to assertDoesNotThrow.
Tests fail if any exception is thrown inside the lambda.
Do not confuse assertDoesNotThrow with assertThrows which expects exceptions.
You can add a custom failure message as an optional first argument.