Sub topic 6
Testing That Code Throws Exceptions
Good code does more than return correct answers. It also refuses bad input. When something goes wrong, Java code often throws an exception. An exception is an object that signals an error and stops normal execution. A test should check that this happens at the right time, with the right type and the right message.
Why Test Exceptions?
Look at the divide method in our Calculator class:
public class Calculator {
public int add(int a, int b) {
return a + b;
}
public int divide(int a, int b) {
if (b == 0) {
throw new IllegalArgumentException("divisor must not be zero");
}
return a / b;
}
}The if check is a rule, and it can break. Someone might delete the check later by mistake. Then dividing by zero would throw an ArithmeticException instead, and callers that expect IllegalArgumentException would fail. A test locks the rule in place.
Using assertThrows
assertThrows is a JUnit assertion that passes only if a piece of code throws a given exception type. It takes two arguments:
- The exception class you expect, such as
IllegalArgumentException.class. - A lambda that runs the code. A lambda is a short block of code you can pass around, written as
() -> ....
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
class CalculatorExceptionTest {
@Test
void divideByZeroThrows() {
Calculator calculator = new Calculator();
IllegalArgumentException ex = assertThrows(
IllegalArgumentException.class,
() -> calculator.divide(10, 0));
assertEquals("divisor must not be zero", ex.getMessage());
}
}assertThrows returns the exception it caught. That lets you check details, such as the message, with normal assertions.
Why the Lambda Matters
You must wrap the call in a lambda. This version is wrong:
// Wrong: this does not compile
assertThrows(IllegalArgumentException.class, calculator.divide(10, 0));Without the lambda, Java would call divide before assertThrows even started, and the exception would escape. In this case the line does not compile at all, because divide returns an int and assertThrows needs code it can run. The lambda hands the code to JUnit so it can run it inside a safe wrapper and catch the exception.
Checking That Code Does Not Throw
Sometimes you want the opposite check. assertDoesNotThrow passes if the code runs without any exception:
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import org.junit.jupiter.api.Test;
class CalculatorSafeTest {
@Test
void divideByNonZeroIsSafe() {
Calculator calculator = new Calculator();
assertDoesNotThrow(() -> calculator.divide(10, 2));
}
}Quick Reference
| Assertion | Passes when |
|---|---|
| `assertThrows(Type.class, code)` | The code throws `Type` or a subclass of it |
| `assertThrowsExactly(Type.class, code)` | The code throws exactly `Type` |
| `assertDoesNotThrow(code)` | The code throws nothing |
Exercise
You write assertThrows(IllegalArgumentException.class, () -> calculator.divide(10, 5)). Does the test pass or fail, and why?
Show answer
It fails. Dividing 10 by 5 returns 2 and throws no exception, so assertThrows reports that the expected exception was never thrown.
Exercise
Write a test that checks calculator.divide(7, 0) throws IllegalArgumentException and that the message contains the word "zero".
Show answer
IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, () -> calculator.divide(7, 0)); then assertTrue(ex.getMessage().contains("zero")); with assertTrue imported statically from org.junit.jupiter.api.Assertions.