Sub topic 6
Testing That Code Throws Exceptions
Most tests check that code gives the right answer. Good code also needs to fail in the right way. If someone asks your calculator to divide by zero, it should refuse with a clear error. It should not return a wrong number. This chapter shows you how to write tests that prove your code throws the right exception at the right time.
Why Test Failures?
An exception is an object Java "throws" to signal that something went wrong. It stops the normal flow of the method. For example, IllegalArgumentException is an exception that means "you passed me a bad value."
Error handling is code too, and it can break. Someone might delete the if check in a later change, or change the message by mistake. A test catches this early. Tests for exceptions also document your rules. A reader of the test learns that zero is not allowed as a divisor.
Here is the class under test again:
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;
}
}Meet assertThrows
assertThrows is a JUnit assertion that runs a piece of code and checks that it throws a given type of exception. It takes two things:
- The class of the exception you expect, such as
IllegalArgumentException.class. - A lambda that holds the code to run. A lambda is a short block of code you can pass around like a value. It is written as
() -> ....
JUnit needs the lambda so it can run the code itself and catch the exception. If you called calculator.divide(10, 0) directly, the exception would fly out before JUnit could check it, and the test would crash.
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() {
// Arrange
Calculator calculator = new Calculator();
// Act and Assert
IllegalArgumentException ex = assertThrows(
IllegalArgumentException.class,
() -> calculator.divide(10, 0));
// Assert more details
assertEquals("divisor must not be zero", ex.getMessage());
}
}Notice that assertThrows gives back the exception it caught. You can store it in a variable and check more things about it, like its message.
What Happens Inside assertThrows
The diagram shows the three ways a call to assertThrows can end.
The middle branch matters most. A passing assertThrows does not end the test. Your code keeps running, so you can add more assertions after it.
Checking the Message and Other Details
Checking only the type is often too weak. Many different bugs can cause an IllegalArgumentException. Checking the message proves the exception came from the check you meant to test.
You can also check your own exception classes. A custom exception is an exception class you write yourself. It can carry extra data. Here is a bank account that refuses to go below zero:
public class InsufficientFundsException extends Exception {
private final int shortfall;
public InsufficientFundsException(int shortfall) {
super("not enough money, short by " + shortfall);
this.shortfall = shortfall;
}
public int getShortfall() {
return shortfall;
}
}public class Account {
private int balance;
public Account(int balance) {
this.balance = balance;
}
public void withdraw(int amount) throws InsufficientFundsException {
if (amount > balance) {
throw new InsufficientFundsException(amount - balance);
}
balance -= amount;
}
public int getBalance() {
return balance;
}
}InsufficientFundsException is a checked exception. A checked exception is one that Java forces you to declare with throws or catch. You might worry the lambda will not compile. It does compile, because the lambda type JUnit uses, called Executable, is allowed to throw anything.
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
class AccountTest {
@Test
void withdrawingTooMuchThrowsAndKeepsBalance() {
Account account = new Account(50);
InsufficientFundsException ex = assertThrows(
InsufficientFundsException.class,
() -> account.withdraw(80));
assertEquals(30, ex.getShortfall());
assertEquals("not enough money, short by 30", ex.getMessage());
assertEquals(50, account.getBalance());
}
}The last line checks something easy to forget: a failed action should not leave the object half-changed. The balance must still be 50.
Exact Type or Any Subtype?
Exceptions form a family tree. NumberFormatException is a subtype of IllegalArgumentException, which is a subtype of RuntimeException. A subtype is a class that extends another class.
assertThrows passes if the thrown exception is the expected type or any subtype. Sometimes you need a stricter check. assertThrowsExactly passes only for the exact class.
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertThrowsExactly;
import org.junit.jupiter.api.Test;
class ExceptionTypeTest {
@Test
void parentTypeAlsoMatches() {
// Integer.parseInt throws NumberFormatException, a subtype
assertThrows(IllegalArgumentException.class,
() -> Integer.parseInt("abc"));
}
@Test
void exactTypeMustMatch() {
assertThrowsExactly(NumberFormatException.class,
() -> Integer.parseInt("abc"));
}
}| Assertion | Passes when the thrown exception is | Typical use |
|---|---|---|
| `assertThrows(X.class, ...)` | `X` or any subtype of `X` | Most tests |
| `assertThrowsExactly(X.class, ...)` | exactly `X`, not a subtype | When the precise class is part of the contract |
| `assertDoesNotThrow(...)` | nothing thrown at all | Proving valid input is accepted |
Proving Code Does Not Throw
assertDoesNotThrow checks the opposite case. It fails if the code throws anything. It can also return the value the code produced:
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class SafeDivideTest {
@Test
void divideByNonZeroWorks() {
Calculator calculator = new Calculator();
int result = assertDoesNotThrow(() -> calculator.divide(10, 2));
assertEquals(5, result);
}
}In plain tests you rarely need this. Any exception already fails a normal test. Use it when you want the test to say clearly "this input must be accepted."
Common Mistakes
Putting too much inside the lambda
Keep only the one call you expect to fail inside the lambda. Look at this weak test:
assertThrows(IllegalArgumentException.class, () -> {
Calculator calculator = new Calculator();
calculator.divide(10, 0);
});If the setup line threw the same exception type, the test would still pass for the wrong reason. Do the setup before assertThrows, as in the earlier examples.
Using the old try/catch pattern
Older code often tests exceptions like this:
try {
calculator.divide(10, 0);
fail("expected an exception");
} catch (IllegalArgumentException ex) {
assertEquals("divisor must not be zero", ex.getMessage());
}It works, but if you forget the fail(...) line, the test passes even when nothing is thrown. assertThrows cannot be forgotten in that way, and it is shorter.
Ignoring the returned exception
If you only check the type, the test is weaker than it could be. When the message or fields matter, store the result and check them.
Exercises
Exercise
Why must the code under test be wrapped in a lambda when you call assertThrows?
Show answer
JUnit has to run the code itself so it can catch the exception and compare it to the expected type. If you call the method directly, the exception is thrown before assertThrows starts, and the test simply errors out.
Exercise
Integer.parseInt("12x") throws NumberFormatException. Does assertThrows(IllegalArgumentException.class, () -> Integer.parseInt("12x")) pass? Does assertThrowsExactly(IllegalArgumentException.class, ...) pass?
Show answer
assertThrows passes, because NumberFormatException is a subtype of IllegalArgumentException. assertThrowsExactly fails, because the thrown class is not exactly IllegalArgumentException.
Exercise
Write a test proving that new Account(10).withdraw(25) throws InsufficientFundsException with a shortfall of 15.
Show answer
Create the account first: Account account = new Account(10); then InsufficientFundsException ex = assertThrows(InsufficientFundsException.class, () -> account.withdraw(25)); then assertEquals(15, ex.getShortfall()); You can also add assertEquals(10, account.getBalance()) to show the balance did not change.