Introduction
We use assertDoesNotThrow to check that a piece of code runs without causing any errors or exceptions.
We use assertDoesNotThrow to check that a piece of code runs without causing any errors or exceptions.
assertDoesNotThrow(() -> {
// code that should not throw an exception
});The code to test is placed inside a lambda expression.
If the code throws an exception, the test will fail.
assertDoesNotThrow(() -> {
int result = 5 / 1;
});someMethod() runs without throwing exceptions.assertDoesNotThrow(() -> someMethod());
This test checks that safeMethod() runs without throwing any exceptions. Since the method only divides numbers safely, the test will pass.
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import org.junit.jupiter.api.Test; public class ExampleTest { public void safeMethod() { // This method does not throw exceptions int a = 10; int b = 2; int c = a / b; } @Test public void testSafeMethod() { assertDoesNotThrow(() -> safeMethod()); } }
If the tested code throws any exception, the test fails immediately.
Use this assertion to ensure stability of code that should not fail.
assertDoesNotThrow confirms code runs without exceptions.
It helps catch unexpected errors early in testing.
Use it to make tests clearer and safer.
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