Sub topic 12
Putting Time Limits on Tests
Most unit tests finish in a few milliseconds. Sometimes, though, a bug makes code run far too long, or it never finishes. An endless loop is one example. A test that hangs can block your whole build. JUnit lets you set a timeout, which is a time limit for a test. If the code takes longer than the limit, the test fails.
This chapter shows the two ways to set a timeout. The first is a method called assertTimeout. The second is an annotation called @Timeout.
Why Time Limits Help
A time limit gives you two things:
- Protection from hangs. A stuck test fails with a clear message, so the build does not just stop and wait.
- A speed check. If a method must be fast, a timeout turns "too slow" into a failing test.
Timing One Piece of Code with assertTimeout
assertTimeout is an assertion. An assertion is a check that makes the test fail if it is false. You give assertTimeout a time limit and the code to run. The time limit is a Duration, which is a Java class for an amount of time. The code is written as a lambda, which is a short block of code you can pass to a method.
This example uses the Calculator class from earlier chapters:
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTimeout;
import java.time.Duration;
import org.junit.jupiter.api.Test;
class CalculatorTimeoutTest {
private final Calculator calculator = new Calculator();
@Test
void addFinishesQuickly() {
int result = assertTimeout(
Duration.ofMillis(100),
() -> calculator.add(2, 3));
assertEquals(5, result);
}
}If the lambda returns a value, assertTimeout hands that value back to you. That lets you check the timing and the answer in the same test.
Timing a Whole Test with @Timeout
Sometimes you want to limit the whole test method, not one line. To do that, put @Timeout on the method. The default unit is seconds. You can pick another unit with unit.
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
class CalculatorLoopTest {
private final Calculator calculator = new Calculator();
@Test
@Timeout(value = 500, unit = TimeUnit.MILLISECONDS)
void manyAdditionsFinishInTime() {
int total = 0;
for (int i = 0; i < 1_000_000; i++) {
total = calculator.add(total, 1);
}
assertEquals(1_000_000, total);
}
}If you put @Timeout on the class, the limit applies to every test method in that class.
Waiting Versus Stopping Early
By default, assertTimeout lets the code run to the end and then checks how long it took. If the code never ends, the test never ends either. assertTimeoutPreemptively behaves differently. "Preemptively" means it stops the code as soon as the limit passes.
| Tool | What it limits | Stops slow code early? |
|---|---|---|
| `assertTimeout` | One block of code | No |
| `assertTimeoutPreemptively` | One block of code | Yes |
| `@Timeout` | A whole test method or class | Yes |
Pick Limits with Room to Spare
Build machines can be slower than your laptop. A limit set too tight makes a test fail at random, which is called a flaky test. Set the limit well above the normal run time.
Exercise
You want a test to fail if a method called loadReport() takes longer than 2 seconds, and loadReport() might get stuck forever. Which tool should you use, and why?
Show answer
Use assertTimeoutPreemptively(Duration.ofSeconds(2), () -> loadReport()) or put @Timeout(2) on the test method. Both stop the code once the limit passes. Plain assertTimeout would wait for loadReport() to finish, so a stuck method would hang the test.
Exercise
What unit does @Timeout(5) use if you do not set unit?
Show answer
Seconds. @Timeout(5) gives the test a limit of 5 seconds.