0
0
JunitHow-ToBeginner ยท 4 min read

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-catch blocks manually instead of assertThrows(), 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

MethodPurposeExample
assertThrowsAsserts that code throws a specific exceptionassertThrows(NullPointerException.class, () -> method())
assertDoesNotThrowAsserts that code does not throw any exceptionassertDoesNotThrow(() -> 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.