0
0
JUnittesting~5 mins

assertDoesNotThrow in JUnit

Choose your learning style9 modes available
Introduction

We use assertDoesNotThrow to check that a piece of code runs without causing any errors or exceptions.

When you want to confirm that a method completes successfully without errors.
When testing code that should not throw exceptions under normal conditions.
When you want to make sure no unexpected exceptions happen during execution.
When verifying that a block of code handles inputs safely without crashing.
Syntax
JUnit
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.

Examples
This checks that dividing 5 by 1 does not throw an exception.
JUnit
assertDoesNotThrow(() -> {
    int result = 5 / 1;
});
This checks that the method someMethod() runs without throwing exceptions.
JUnit
assertDoesNotThrow(() -> someMethod());
Sample Program

This test checks that safeMethod() runs without throwing any exceptions. Since the method only divides numbers safely, the test will pass.

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

If the tested code throws any exception, the test fails immediately.

Use this assertion to ensure stability of code that should not fail.

Summary

assertDoesNotThrow confirms code runs without exceptions.

It helps catch unexpected errors early in testing.

Use it to make tests clearer and safer.