W3docs

How to test that no exception is thrown?

To test that no exception is thrown in a Java method, you can use the assertDoesNotThrow method from the org.junit.jupiter.api.Assertions class (part of the JUnit 5 library).

To test that no exception is thrown in a Java method, you can use the assertDoesNotThrow method from the org.junit.jupiter.api.Assertions class (part of the JUnit 5 library).

Here is an example of how to use assertDoesNotThrow to test that a method does not throw an exception:


import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;

public class NoExceptionTest {

    @Test
    public void testNoException() {
        assertDoesNotThrow(() -> {
            // code that is expected to not throw an exception
        });
    }

}

The assertDoesNotThrow method takes a org.junit.jupiter.api.function.Executable lambda as an argument, which is a block of code that is expected to not throw any exceptions. If the code block does throw an exception, assertDoesNotThrow will fail the test.

You can also use the try-catch statement to test that a method does not throw an exception:


import static org.junit.jupiter.api.Assertions.fail;
import org.junit.jupiter.api.Test;

public class TryCatchTest {

    @Test
    public void testWithTryCatch() {
        try {
            // code that is expected to not throw an exception
        } catch (Exception e) {
            fail("Exception was thrown");
        }
    }

}

In this case, the test will fail if an exception is thrown in the try block.