0
0
JunitHow-ToBeginner ยท 3 min read

How to Use assertThrows in JUnit for Exception Testing

Use assertThrows in JUnit to check if a specific exception is thrown by a code block. It takes the expected exception class and a lambda containing the code that should throw the exception, returning the caught exception for further checks.
๐Ÿ“

Syntax

The assertThrows method requires two main parts: the expected exception class and an executable block of code (usually a lambda) that should throw that exception.

It returns the thrown exception, allowing you to assert on its message or properties.

java
Throwable exception = assertThrows(ExpectedException.class, () -> {
    // code that should throw the exception
});
๐Ÿ’ป

Example

This example shows how to test that dividing by zero throws an ArithmeticException with the expected message.

java
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertEquals;

import org.junit.jupiter.api.Test;

public class CalculatorTest {

    @Test
    void testDivideByZeroThrows() {
        ArithmeticException exception = assertThrows(ArithmeticException.class, () -> {
            int result = divide(10, 0);
        });
        assertEquals("/ by zero", exception.getMessage());
    }

    int divide(int a, int b) {
        return a / b;
    }
}
Output
Test passed
โš ๏ธ

Common Pitfalls

  • Not using a lambda or executable block, which causes compilation errors.
  • Expecting the wrong exception type, leading to test failures.
  • Not asserting on the exception message when needed, missing detailed verification.
java
/* Wrong: passing method call directly, executes before assertThrows */
assertThrows(NullPointerException.class, () -> divide(10, 0));

/* Right: use lambda to defer execution */
assertThrows(NullPointerException.class, () -> divide(10, 0));
๐Ÿ“Š

Quick Reference

Remember these key points when using assertThrows:

  • Use a lambda or method reference for the code that throws.
  • Specify the exact exception class expected.
  • Capture the returned exception to assert on its message or properties.
  • Use it to make your tests clear and focused on exception behavior.
โœ…

Key Takeaways

Use assertThrows with a lambda to test for expected exceptions in JUnit.
Always specify the exact exception class you expect to be thrown.
Capture the thrown exception to verify its message or details if needed.
Avoid calling the tested method directly inside assertThrows to prevent premature execution.
assertThrows makes your tests clearer and more reliable for exception handling.