0
0
JunitHow-ToBeginner ยท 3 min read

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 assertDoesNotThrow with assertThrows, 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

UsageDescription
assertDoesNotThrow(() -> code)Passes if code runs without exceptions
assertDoesNotThrow(() -> code, "message")Fails with message if exception thrown
Use with lambdas or method referencesClean 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.