Verify that a test method fails if it exceeds the specified timeout
Preconditions (2)
✅ Expected Result: The test fails due to exceeding the 2-second timeout
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import java.util.concurrent.TimeUnit; public class TimeoutTest { @Test @Timeout(value = 2, unit = TimeUnit.SECONDS) void testTimeoutExceeded() throws InterruptedException { // Simulate long running task Thread.sleep(3000); // 3 seconds sleep } }
The test method testTimeoutExceeded is annotated with @Timeout(2 seconds). This means JUnit will fail the test if it runs longer than 2 seconds.
Inside the test, Thread.sleep(3000) pauses execution for 3 seconds, which exceeds the timeout.
When running this test, JUnit detects the timeout breach and fails the test automatically.
This example shows how to use the @Timeout annotation to prevent tests from running too long.
Now add data-driven testing with 3 different timeout values and corresponding sleep durations to verify timeout behavior
@Timeout annotation in JUnit tests?@Test
@Timeout(value = 2, unit = TimeUnit.SECONDS)
void testSleep() throws InterruptedException {
Thread.sleep(3000);
}What will happen when this test runs?@Timeout(1) but does not compile. What is the error?@Test
@Timeout(1)
void testMethod() {
// test code
}Pass the test and this pattern moves unknown