0
0
JUnittesting~5 mins

assertThrows usage in JUnit

Choose your learning style9 modes available
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.

When you want to test that a method throws an exception for invalid input.
When you want to make sure your code handles errors properly.
When you want to confirm that a specific error type is thrown in a certain situation.
Syntax
JUnit
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.

Examples
This checks that parsing a non-number string throws an IllegalArgumentException.
JUnit
assertThrows(IllegalArgumentException.class, () -> {
    Integer.parseInt("abc");
});
This checks that calling a method on null throws NullPointerException.
JUnit
assertThrows(NullPointerException.class, () -> {
    String s = null;
    s.length();
});
Sample Program

This test checks that dividing by zero throws an ArithmeticException.

JUnit
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;
        });
    }
}
OutputSuccess
Important Notes

Always specify the exact exception class you expect to catch.

Use lambda expressions to keep the test code clean and focused.

Summary

assertThrows helps verify that errors happen when they should.

It improves test reliability by checking for specific exceptions.