How to Use @Timeout Annotation in JUnit for Test Time Limits
Use the
@Timeout annotation in JUnit to specify a maximum time a test should run. If the test exceeds this time, it fails automatically. You can set the timeout duration and time unit directly on the annotation.Syntax
The @Timeout annotation is placed above a test method or class to set a maximum execution time. It takes two main parameters: value for the duration and unit for the time unit (like seconds or milliseconds). If the test runs longer than this, JUnit fails it.
java
@Timeout(value = 5, unit = TimeUnit.SECONDS) void testMethod() { // test code }
Example
This example shows a test that will fail if it runs longer than 2 seconds. The test sleeps for 3 seconds, so it will fail due to timeout.
java
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import java.util.concurrent.TimeUnit; import static org.junit.jupiter.api.Assertions.assertTrue; public class TimeoutExampleTest { @Test @Timeout(value = 2, unit = TimeUnit.SECONDS) void testTimeoutFailure() throws InterruptedException { Thread.sleep(3000); // Sleep 3 seconds assertTrue(true); } @Test @Timeout(5) // default unit is seconds void testTimeoutSuccess() throws InterruptedException { Thread.sleep(1000); // Sleep 1 second assertTrue(true); } }
Output
Test result: testTimeoutFailure FAILED due to timeout after 2 seconds
Test result: testTimeoutSuccess PASSED
Common Pitfalls
- Not importing
java.util.concurrent.TimeUnitwhen specifying the unit causes errors. - Using
@Timeouton a class sets the timeout for all tests inside it, which might be unintended. - For very short timeouts, tests might fail due to environment slowness; choose reasonable durations.
- Legacy JUnit 4 uses a different timeout approach;
@Timeoutis for JUnit 5 and later.
java
/* Wrong: Missing import for TimeUnit */ @Timeout(value = 1, unit = TimeUnit.SECONDS) // Error: TimeUnit not recognized without import void test() {} /* Right: Import TimeUnit and use it */ import java.util.concurrent.TimeUnit; @Timeout(value = 1, unit = TimeUnit.SECONDS) void test() {}
Quick Reference
| Parameter | Description | Default |
|---|---|---|
| value | Timeout duration (number) | Required |
| unit | Time unit from java.util.concurrent.TimeUnit | SECONDS |
| threadMode | Whether timeout applies to test thread or all threads | DEFAULT |
Key Takeaways
Use @Timeout to automatically fail tests that run longer than a specified time.
Specify both value and unit for clear timeout duration, default unit is seconds.
Import java.util.concurrent.TimeUnit to avoid errors when setting the unit.
Applying @Timeout at class level sets timeout for all tests inside the class.
Choose reasonable timeout values to avoid false failures due to slow environments.