Introduction
We use assertThrows to check if a piece of code correctly throws an error when something goes wrong. This helps us catch mistakes early.
We use assertThrows to check if a piece of code correctly throws an error when something goes wrong. This helps us catch mistakes early.
assertThrows(ExpectedException.class, () -> {
// code that should throw the exception
});The first argument is the type of exception you expect.
The second argument is a lambda with the code that should throw the exception.
assertThrows(IllegalArgumentException.class, () -> { Integer.parseInt("abc"); });
assertThrows(NullPointerException.class, () -> {
String s = null;
s.length();
});This test checks that dividing by zero throws an ArithmeticException.
import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.api.Test; public class ExceptionTest { @Test void testDivideByZero() { assertThrows(ArithmeticException.class, () -> { int result = 10 / 0; }); } }
Always specify the exact exception class you expect to catch.
Use lambda expressions to keep the test code clean and focused.
assertThrows helps verify that errors happen when they should.
It improves test reliability by checking for specific exceptions.
assertThrows in JUnit testing?assertThrows is used to test if a particular exception occurs when running a piece of code.assertThrows specifically checks for exceptions.assertThrows in JUnit 5?assertThrows(Exception.class, Executable) where Executable is a lambda or method reference.assertThrows(IllegalArgumentException.class, () -> {
throw new IllegalArgumentException("Invalid argument");
});IllegalArgumentException, which matches the expected exception class.assertThrows(NullPointerException.class, () -> {
String s = null;
s.length();
});s.length() on a null string throws NullPointerException.NullPointerException.class, matching the thrown exception.void testDivideByZero() {
ArithmeticException thrown = assertThrows(ArithmeticException.class, () -> {
int result = 10 / 0;
});
assertEquals("/ by zero", thrown.getMessage());
}thrown.Pass the test and this pattern moves unknown