Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Show two ways to fail a JUnit 5 test that takes longer than 2 seconds, explain the difference between @Timeout and assertTimeout, and how to set a default timeout for all tests.

We can annotate the test with @Timeout(value = 2, unit = TimeUnit.SECONDS), or wrap the slow code in assertTimeout(Duration.ofSeconds(2), () -> ...). assertTimeout runs the code in the same thread and only fails after the code has finished, while assertTimeoutPreemptively and @Timeout stop the work when the time is up. A default for all tests goes in junit-platform.properties, for example junit.jupiter.execution.timeout.default = 5 s.

Why this question is asked

Timeouts look like a small feature, but they decide whether a stuck test fails in two seconds with a clear message or hangs the pipeline for an hour. Interviewers ask this because the two APIs behave differently in a way that matters: one waits for slow code to finish, the other abandons it, and abandoning code that runs on another thread can break transactions and other thread-bound state. In this answer, we will write the test both ways, compare the same-thread and preemptive styles, look at @Timeout's thread modes, set a default for the whole project, and see how to keep timeouts out of the way while debugging.

1The Code We Want to Limit

Suppose we have a report service whose generate() method should finish within two seconds, and a test that should fail when it does not. A timeout here is an assertion about time: the result may be correct, but if it arrives too late the test should still fail.

Java
class ReportService {
Report generate(long millis) throws InterruptedException {
Thread.sleep(millis); // stands in for real work
return new Report("ok");
}
}

2Way 1: The @Timeout Annotation

@Timeout on a test method sets a limit for that method. On a class, it applies to every test method in the class, and a method's own annotation overrides it. The unit defaults to seconds, so @Timeout(2) means two seconds.

Java
@Test
@Timeout(value = 2, unit = TimeUnit.SECONDS)
void generatesReportQuickly() throws Exception {
service.generate(3_000);
}
// generatesReportQuickly() timed out after 2 seconds (fails at about 2 s)

By default, the test still runs on the normal test thread. JUnit starts a timer, and when the time is up it interrupts that thread. Thread.sleep() reacts to the interrupt by throwing InterruptedException, so the test stops after about two seconds and fails with a timeout message. Notice the condition: code that ignores interrupts, such as a busy loop or some blocking socket reads, keeps running until it ends on its own, and the test fails only then.

3Way 2: assertTimeout and assertTimeoutPreemptively

The assertion versions limit only a part of the test, the lambda we pass, which is useful when the setup is slow but only one call is under test. There are two of them and they behave very differently.

Java
@Test
void sameThread() {
Report r = assertTimeout(Duration.ofSeconds(2), () -> service.generate(3_000));
// fails after about 3 s: execution exceeded timeout of 2000 ms by 1003 ms
}
@Test
void preemptive() {
Report r = assertTimeoutPreemptively(Duration.ofSeconds(2), () -> service.generate(3_000));
// fails after about 2 s: execution timed out after 2000 ms
}
@Test
void fastEnough() {
Report r = assertTimeout(Duration.ofSeconds(2), () -> service.generate(100));
assertEquals("ok", r.status()); // passes; assertTimeout returns the lambda's result
}
Choosing a timeout style
StyleThreadWhen the limit passesThread-bound state
assertTimeouttest threadwaits, then fails with the overrunkept
assertTimeoutPreemptivelyseparate threadfails at once, abandons the codelost
@Timeout (default SAME_THREAD)test threadinterrupts the test threadkept
@Timeout SEPARATE_THREADseparate threadfails at oncelost

assertTimeout runs the lambda in the current thread, waits for it to finish however long it takes, and then compares the elapsed time with the limit. So it reports how much the code overran, but it does not save us from a hang: if the code never returns, neither does the test.

assertTimeoutPreemptively runs the lambda in a different thread and, when the limit passes, abandons it and fails immediately. That protects against hangs, but there is a catch. Anything bound to the test thread is not visible in the other thread. A Spring test transaction, a security context, an MDC logging context or any ThreadLocal set up by the test belongs to the test thread, so the code in the lambda runs without it. Database changes made there may not roll back with the test, and the results can be confusing.

4Thread Modes of @Timeout

@Timeout also has a threadMode attribute (added in JUnit 5.9). The default, SAME_THREAD, is what we saw: the test runs on its usual thread and is interrupted. SEPARATE_THREAD runs the test method on another thread, like assertTimeoutPreemptively, so it can fail on time even when the code ignores interrupts, at the price of losing thread-bound state. INFERRED uses the configured default.

Java
@Test
@Timeout(value = 2, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
void stopsEvenIfInterruptsAreIgnored() {
while (true) { } // a busy loop never checks for interrupts
}
// fails after about 2 s; the busy thread is abandoned

So for most tests, the default same-thread mode is the safer choice, and SEPARATE_THREAD is for the rare test whose code cannot be interrupted.

5A Default Timeout for Every Test

Annotating every test is tedious and easy to forget, so JUnit lets us set defaults in src/test/resources/junit-platform.properties. The value is a number and a unit, such as 5 s, 500 ms or 1 m.

Properties
# src/test/resources/junit-platform.properties
junit.jupiter.execution.timeout.default = 5 s # every testable and lifecycle method
junit.jupiter.execution.timeout.testable.method.default = 5 s # @Test, @RepeatedTest, @ParameterizedTest ...
junit.jupiter.execution.timeout.test.method.default = 2 s # only @Test methods
junit.jupiter.execution.timeout.lifecycle.method.default = 30 s # @BeforeAll, @BeforeEach ...
junit.jupiter.execution.timeout.beforeall.method.default = 2 m # e.g. starting containers

The more specific keys win over the general one, and an explicit @Timeout on a test wins over all of them. A generous default, five or ten seconds for unit tests and minutes for container startup, does not get in anyone's way but turns a hang into a failure.

6Keeping Timeouts Out of the Way While Debugging

When we stop at a breakpoint, the clock keeps running, and the test fails as soon as we resume. JUnit's junit.jupiter.execution.timeout.mode setting has three values: enabled, disabled and disabled_on_debug. With disabled_on_debug, JUnit detects that the JVM was started with a debugger agent and ignores timeouts for that run, while CI still enforces them.

Properties
junit.jupiter.execution.timeout.mode = disabled_on_debug

7Follow-up questions

Why does assertTimeout return a value?

It returns whatever the lambda returns, so we can time a call and check its result in one place, as in Report r = assertTimeout(..., () -> service.generate(100)). There are versions for lambdas that return nothing as well.

Should a timeout be used to test performance?

Only as a coarse guard. Test machines vary a lot, and a CI runner under load can be several times slower than a laptop, so tight limits create flaky tests. Real performance checks belong in benchmarks such as JMH or load tests, with timeouts in unit tests set well above normal run times.

Does @Timeout on a class also limit @BeforeEach methods?

No. On a class it applies to the test methods (and to the testable methods in nested classes); lifecycle methods use their own @Timeout or the lifecycle defaults from the configuration.

8Conclusion

In this answer, we failed a slow test in two ways: with @Timeout(value = 2, unit = TimeUnit.SECONDS), which by default interrupts the test thread, and with the assertTimeout family. assertTimeout runs in the same thread and fails only after the code finishes, while assertTimeoutPreemptively and @Timeout with SEPARATE_THREAD abandon the code on time but lose thread-bound state such as transactions. Defaults for all tests go in junit-platform.properties, and the disabled_on_debug mode keeps them from firing at breakpoints.

What to say in the interviewAbout 80 seconds aloud

Open with

There are two ways. The first is the @Timeout annotation, for example @Timeout with value 2 and unit seconds, on the method or on the class. By default it runs the test on the normal thread and interrupts it when the time is up, so code that responds to interrupts stops at two seconds and the test fails.

Then, if they want more

The second is the assertion: assertTimeout with Duration.ofSeconds(2) and a lambda.

The important difference is that assertTimeout runs the lambda in the same thread and waits for it to finish, then fails if it took too long, so it tells me the overrun but does not protect against a hang. assertTimeoutPreemptively runs the lambda in another thread and fails as soon as the limit passes.

The cost of the separate thread is that thread-bound state is lost, like a Spring test transaction or a ThreadLocal, so I prefer same-thread versions unless the code can truly hang. @Timeout has the same choice through threadMode, SAME_THREAD by default or SEPARATE_THREAD.

For a project-wide default I put junit.jupiter.execution.timeout.default = 5 s in junit-platform.properties, with more specific keys for test methods or lifecycle methods, and I set timeout.mode to disabled_on_debug so breakpoints do not trigger failures.

About this answer

Last updated
12 November 2026
Versions it names
JUnit 5
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
JUnit user guide
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Show two ways to fail a JUnit 5 test that takes longer than 2 seconds, explain the...": https://scrivio-interview-library.netlify.app/java/junit/e2175adda2/