How to Assert Exception in JUnit Tests
In JUnit, you can assert that a method throws an exception using
assertThrows(). This method takes the expected exception class and a lambda with the code that should throw the exception, and it passes if the exception occurs.Syntax
The assertThrows() method in JUnit has this syntax:
assertThrows(ExpectedException.class, () -> { codeThatThrows(); });
Here, ExpectedException.class is the type of exception you expect, and the lambda contains the code that should throw it.
java
assertThrows(IllegalArgumentException.class, () -> { // code that should throw IllegalArgumentException });
Example
This example shows how to test that a method throws IllegalArgumentException when given a negative number.
java
import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; class Calculator { int squareRoot(int number) { if (number < 0) { throw new IllegalArgumentException("Negative number not allowed"); } return (int) Math.sqrt(number); } } public class CalculatorTest { @Test void testSquareRootThrowsException() { Calculator calc = new Calculator(); IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, () -> { calc.squareRoot(-1); }); // Optional: check exception message assertEquals("Negative number not allowed", thrown.getMessage()); } }
Output
Test passed
Common Pitfalls
Common mistakes when asserting exceptions in JUnit include:
- Using
try-catchblocks manually instead ofassertThrows(), which is less clean and can miss failures. - Not specifying the exact exception class, which can cause false positives.
- Not including the code that throws the exception inside the lambda, causing the test to pass incorrectly.
java
/* Wrong way: Using try-catch manually */ @Test void testExceptionWrong() { Calculator calc = new Calculator(); try { calc.squareRoot(-1); fail("Expected exception not thrown"); } catch (IllegalArgumentException e) { // test passes } } /* Right way: Using assertThrows */ @Test void testExceptionRight() { Calculator calc = new Calculator(); assertThrows(IllegalArgumentException.class, () -> calc.squareRoot(-1)); }
Quick Reference
| Method | Purpose | Example |
|---|---|---|
| assertThrows | Asserts that code throws a specific exception | assertThrows(NullPointerException.class, () -> method()) |
| assertDoesNotThrow | Asserts that code does not throw any exception | assertDoesNotThrow(() -> method()) |
Key Takeaways
Use assertThrows() to check for exceptions in JUnit tests cleanly and clearly.
Always specify the exact exception class you expect to avoid false positives.
Put the code that should throw the exception inside the lambda passed to assertThrows().
Avoid manual try-catch blocks for exception testing; prefer assertThrows() for readability and correctness.
You can capture the thrown exception from assertThrows() to check its message or properties.