0
0
JunitHow-ToBeginner ยท 3 min read

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.TimeUnit when specifying the unit causes errors.
  • Using @Timeout on 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; @Timeout is 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

ParameterDescriptionDefault
valueTimeout duration (number)Required
unitTime unit from java.util.concurrent.TimeUnitSECONDS
threadModeWhether timeout applies to test thread or all threadsDEFAULT
โœ…

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.