0
0
JUnittesting~5 mins

Testing no exception thrown in JUnit

Choose your learning style9 modes available
Introduction

We check that a piece of code runs without errors to make sure it works as expected.

When you want to confirm a method completes successfully without crashing.
When testing code that should not throw any errors under normal conditions.
When verifying that input values do not cause exceptions.
When ensuring that setup or initialization code runs smoothly.
When validating that a function handles edge cases without exceptions.
Syntax
JUnit
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.

Examples
Checks that simple math does not throw an exception.
JUnit
assertDoesNotThrow(() -> {
    int result = 5 + 3;
});
Verifies adding an item to a list does not cause errors.
JUnit
assertDoesNotThrow(() -> {
    List<String> list = new ArrayList<>();
    list.add("item");
});
Tests that handling a null value does not throw an exception.
JUnit
assertDoesNotThrow(() -> {
    String text = null;
    if (text == null) {
        text = "default";
    }
});
Sample Program

This test checks that adding items to a list does not throw any exceptions.

JUnit
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");
        });
    }
}
OutputSuccess
Important Notes

Use assertDoesNotThrow to keep tests clear and focused on error-free execution.

It helps catch unexpected exceptions early in development.

Summary

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.