Introduction
We check that a piece of code runs without errors to make sure it works as expected.
We check that a piece of code runs without errors to make sure it works as expected.
assertDoesNotThrow(() -> {
// code that should not throw an exception
});This syntax uses a lambda expression to run the code.
If the code throws an exception, the test will fail.
assertDoesNotThrow(() -> {
int result = 5 + 3;
});assertDoesNotThrow(() -> {
List<String> list = new ArrayList<>();
list.add("item");
});assertDoesNotThrow(() -> {
String text = null;
if (text == null) {
text = "default";
}
});This test checks that adding items to a list does not throw any exceptions.
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; public class NoExceptionTest { @Test void testNoExceptionThrown() { assertDoesNotThrow(() -> { List<String> items = new ArrayList<>(); items.add("apple"); items.add("banana"); }); } }
Use assertDoesNotThrow to keep tests clear and focused on error-free execution.
It helps catch unexpected exceptions early in development.
Use assertDoesNotThrow to confirm code runs without errors.
This improves confidence that your code handles inputs safely.
It is simple and keeps tests clean and readable.
assertDoesNotThrow in JUnit testing?assertDoesNotThrowassertDoesNotThrow ensures smooth execution without errors.myMethod() using JUnit 5?assertDoesNotThrow takes a lambda expression or executable block, like () -> myMethod().assertDoesNotThrow(() -> myMethod()); correctly uses a lambda expression. assertThrows(() -> myMethod()); tests for exceptions, non-existent methods like assertNoException(myMethod()); won't work, and assertDoesNotThrow(myMethod); misses lambda syntax.assertDoesNotThrow(() -> {
int result = 10 / 2;
System.out.println(result);
});assertDoesNotThrow passes the test.@Test
void testSafeMethod() {
assertDoesNotThrow(mySafeMethod());
}
void mySafeMethod() {
// safe code
}mySafeMethod() immediately and passes its result, which is void, instead of passing a lambda.() -> mySafeMethod() to defer execution and catch exceptions.processData(String input) does not throw exceptions for any non-null input. Which JUnit 5 test code correctly tests this for inputs "hello" and "world" using assertDoesNotThrow?processData does not throw exceptions for both inputs "hello" and "world".assertDoesNotThrow, ensuring both run without exceptions.assertDoesNotThrow(processData(...)) calls execute methods immediately without lambdas, which is incorrect. assertDoesNotThrow(() -> processData("hello", "world")); passes two arguments to a one-argument method. assertDoesNotThrow(() -> { processData(null); }); tests null input, which is not required.Pass the test and this pattern moves unknown