Sub topic 12
Putting Time Limits on Tests
Some bugs do not give a wrong answer. They give the right answer too slowly, or they never finish at all. A loop that never ends, a network call that hangs, or a method that suddenly takes ten seconds instead of ten milliseconds can all slip past ordinary assertions. JUnit 5 lets you put a time limit on a test so that slowness counts as a failure.
This chapter covers three tools:
assertTimeout, an assertion that checks how long a piece of code took.assertTimeoutPreemptively, an assertion that stops the code as soon as the limit passes.@Timeout, an annotation that puts a limit on a whole test method or class.
Why time limits matter
A timeout is a maximum amount of time that code is allowed to run. If the code runs longer, the test fails.
Timeouts help in two situations:
- Catching performance regressions. A regression is a bug that breaks something that used to work. If a sort method used to finish in 5 ms and a change makes it take 2 seconds, a timeout tells you right away.
- Stopping hung tests. A test that never ends can block your whole build. A timeout turns "stuck forever" into a clear failure with a message.
The code under test
The examples use this small class. It simulates slow work by sleeping 10 ms per page.
public class ReportBuilder {
public String build(int pages) throws InterruptedException {
Thread.sleep(pages * 10L);
return "Report with " + pages + " pages";
}
}Thread.sleep pauses the current thread. A thread is one path of execution inside a running program. This matters later, because some timeout tools run your code in a different thread.
assertTimeout: wait, then judge
assertTimeout takes a Duration (a Java type that holds an amount of time) and a lambda containing the code to check. It runs the code, waits for it to finish, and fails if it took longer than the limit.
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 ReportBuilderTimeoutTest {
private final ReportBuilder builder = new ReportBuilder();
@Test
void smallReportIsFast() {
String report = assertTimeout(
Duration.ofMillis(500),
() -> builder.build(5));
assertEquals("Report with 5 pages", report);
}
@Test
void largeReportIsTooSlow() {
assertTimeout(Duration.ofMillis(100), () -> builder.build(50));
}
}The first test passes. Five pages take about 50 ms, which is well under 500 ms. assertTimeout also returns the lambda's result, so you can check the value afterwards.
The second test fails. Fifty pages take about 500 ms, and the limit is 100 ms. JUnit reports a message like this:
org.opentest4j.AssertionFailedError: execution exceeded timeout of 100 ms by 402 msThe message tells you the limit and how far over it the code went.
The lambda may throw checked exceptions such as InterruptedException, so you do not need a try/catch inside it.
assertTimeoutPreemptively: stop the code early
"Preemptively" means "before it finishes." This version runs your code in a separate thread. When the limit passes, JUnit stops waiting, tries to interrupt that thread, and fails the test right away.
import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
import java.time.Duration;
import org.junit.jupiter.api.Test;
class PreemptiveTimeoutTest {
@Test
void stopsAHangingLoop() {
assertTimeoutPreemptively(Duration.ofMillis(200), () -> {
while (true) {
Thread.sleep(10);
}
});
}
}The loop never ends, but the test fails after about 200 ms with:
org.opentest4j.AssertionFailedError: execution timed out after 200 msWith plain assertTimeout, the same test would hang forever.
The catch with a separate thread
Running in another thread has a side effect. Some code stores data per thread using ThreadLocal. Frameworks use this for things like database transactions and security logins. The new thread cannot see that data, so code that works normally can behave differently inside assertTimeoutPreemptively.
This diagram shows how the two assertions decide the result.
@Timeout: a limit for the whole test
Sometimes you want to limit the entire test method, not one line. The @Timeout annotation does that. An annotation is a label starting with @ that tells JUnit how to treat a method or class.
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 AnnotatedTimeoutTest {
private final ReportBuilder builder = new ReportBuilder();
@Test
@Timeout(2)
void finishesWithinTwoSeconds() throws InterruptedException {
assertEquals("Report with 3 pages", builder.build(3));
}
@Test
@Timeout(value = 100, unit = TimeUnit.MILLISECONDS)
void finishesWithin100Milliseconds() throws InterruptedException {
assertEquals("Report with 50 pages", builder.build(50));
}
}Points to notice:
- The default unit is seconds.
@Timeout(2)means 2 seconds, not 2 milliseconds. This is a common mistake. - Use
unit = TimeUnit.MILLISECONDSfor smaller limits. - The second test fails, because 50 pages take about 500 ms.
By default, @Timeout runs the test in the same thread. When time runs out, JUnit interrupts the thread. Thread.sleep reacts to interrupts, so the test stops. Code that ignores interrupts, such as a busy loop with no sleep, keeps running until it ends, and then the test fails.
Since JUnit 5.9 you can ask for a separate thread instead, which works like assertTimeoutPreemptively:
@Timeout(value = 1, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)Putting @Timeout on a class
If you place @Timeout on the class, every test method in it gets that limit, including tests in @Nested classes. A method's own @Timeout overrides the class value.
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
@Timeout(value = 500, unit = TimeUnit.MILLISECONDS)
class AllTestsAreQuickTest {
@Test
void quickOne() throws InterruptedException {
Thread.sleep(50);
}
@Test
@Timeout(3)
void allowedToBeSlower() throws InterruptedException {
Thread.sleep(1000);
}
}A default timeout for the whole project
You can set one limit for every test without touching any test class. Create the file src/test/resources/junit-platform.properties:
junit.jupiter.execution.timeout.default = 5 s
junit.jupiter.execution.timeout.mode = disabled_on_debugThe first line gives every test a 5-second limit unless it has its own @Timeout. The second line turns timeouts off when you run tests in a debugger. Pausing on a breakpoint would otherwise make every test time out.
Choosing the right tool
| Tool | Limits | Thread | Stops hung code? | Good for |
|---|---|---|---|---|
| `assertTimeout` | One block of code | Same | No | Checking that a step is fast enough |
| `assertTimeoutPreemptively` | One block of code | Separate | Yes | Code that might hang, with no thread-local data |
| `@Timeout` | Whole test method or class | Same (default) | Yes, if code reacts to interrupts | A safety limit for whole tests |
Avoiding flaky timeouts
A flaky test passes sometimes and fails other times without any code change. Tight timeouts are a common cause. Build servers are often slower and busier than your laptop.
- Set limits several times higher than the normal run time. If code takes 20 ms, a 1-second limit still catches a real hang.
- Never use timeouts to compare small speed differences. Use a benchmarking tool for that.
- If a timeout test fails only on the build server, raise the limit before you hunt for a bug.
Exercise
A test uses @Timeout(500) and the author expects it to fail if the method takes more than half a second. The method takes 2 seconds, but the test passes. Why?
Show answer
The default unit for @Timeout is seconds, so @Timeout(500) allows 500 seconds. Write @Timeout(value = 500, unit = TimeUnit.MILLISECONDS) instead.
Exercise
You test a method that sometimes goes into an endless loop. You wrap it in assertTimeout(Duration.ofSeconds(1), ...), but the build hangs. What should you change?
Show answer
assertTimeout waits for the code to finish, so an endless loop blocks forever. Use assertTimeoutPreemptively, which runs the code in a separate thread and fails as soon as the limit passes. You could also use @Timeout with threadMode = Timeout.ThreadMode.SEPARATE_THREAD.
Exercise
Write a test that checks that new ReportBuilder().build(2) returns "Report with 2 pages" and finishes within 300 milliseconds, using one assertion for the time and one for the value.
Show answer
Use String report = assertTimeout(Duration.ofMillis(300), () -> new ReportBuilder().build(2)); followed by assertEquals("Report with 2 pages", report); inside a method annotated with @Test, with static imports for assertTimeout and assertEquals and an import for java.time.Duration.