0
0
JunitHow-ToBeginner ยท 3 min read

How to Use assertTimeout in JUnit for Timeout Testing

Use assertTimeout in JUnit to check that a block of code completes within a given duration. It takes a Duration and an executable lambda, failing the test if the code runs longer than the timeout.
๐Ÿ“

Syntax

The assertTimeout method requires two main parts:

  • Duration: The maximum time allowed for the code to run, specified using Duration.ofSeconds() or similar.
  • Executable: A lambda or method reference containing the code to test.

If the code runs longer than the duration, the test fails.

java
assertTimeout(Duration.ofSeconds(2), () -> {
    // code to test
});
๐Ÿ’ป

Example

This example shows how to use assertTimeout to verify a method finishes within 1 second.

java
import static org.junit.jupiter.api.Assertions.assertTimeout;
import java.time.Duration;
import org.junit.jupiter.api.Test;

public class TimeoutTest {

    @Test
    void testFastMethod() throws InterruptedException {
        assertTimeout(Duration.ofSeconds(1), () -> {
            Thread.sleep(500); // Simulate work
        });
    }

    @Test
    void testSlowMethod() throws InterruptedException {
        assertTimeout(Duration.ofSeconds(1), () -> {
            Thread.sleep(1500); // Simulate slow work
        });
    }
}
Output
testFastMethod: PASSED testSlowMethod: FAILED (execution exceeded timeout of 1 second)
โš ๏ธ

Common Pitfalls

  • Using assertTimeout does not stop the code when the timeout is exceeded; it waits for completion and then fails if too slow.
  • To abort execution on timeout, use assertTimeoutPreemptively instead.
  • Not specifying the timeout duration correctly can cause unexpected test failures or passes.
java
/* Wrong: expecting immediate stop on timeout (this will not stop early) */
assertTimeout(Duration.ofSeconds(1), () -> {
    Thread.sleep(2000); // This will run fully before failing
});

/* Right: use assertTimeoutPreemptively to abort early */
assertTimeoutPreemptively(Duration.ofSeconds(1), () -> {
    Thread.sleep(2000); // This will be aborted after 1 second
});
๐Ÿ“Š

Quick Reference

MethodDescription
assertTimeout(Duration, Executable)Fails if code runs longer than duration but waits for completion
assertTimeoutPreemptively(Duration, Executable)Fails and aborts code execution if timeout exceeded
Duration.ofSeconds(long)Creates a duration of specified seconds
ExecutableFunctional interface for code block to test
โœ…

Key Takeaways

Use assertTimeout to verify code completes within a set time without aborting execution.
Specify the timeout duration clearly using Duration methods like ofSeconds().
assertTimeout waits for code to finish before failing; use assertTimeoutPreemptively to stop early.
Always wrap the code to test inside a lambda or method reference passed to assertTimeout.
Timeout tests help catch performance regressions and slow operations in your code.