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).
Here is an example of how to use assertDoesNotThrow
to test that a method does not throw an exception:
import org.junit.jupiter.api.Assertions;
public class NoExceptionTest {
@Test
public void testNoException() {
assertDoesNotThrow(() -> {
// code that is expected to not throw an exception
});
}
}
The assertDoesNotThrow
method takes a 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:
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.
I hope this helps. Let me know if you have any questions.