Test Overview
This test checks that a method completes within a specified time limit using JUnit's timeout annotation. It verifies the test fails if the method runs longer than allowed.
This test checks that a method completes within a specified time limit using JUnit's timeout annotation. It verifies the test fails if the method runs longer than allowed.
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import java.util.concurrent.TimeUnit; import static org.junit.jupiter.api.Assertions.*; public class TimeoutTest { @Test @Timeout(value = 2, unit = TimeUnit.SECONDS) void testMethodCompletesWithinTimeout() throws InterruptedException { // Simulate work that takes 1 second Thread.sleep(1000); assertTrue(true); } @Test @Timeout(value = 1, unit = TimeUnit.SECONDS) void testMethodExceedsTimeout() throws InterruptedException { // Simulate work that takes 2 seconds Thread.sleep(2000); assertTrue(true); } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test runner starts and loads TimeoutTest class | JUnit test environment initialized | - | PASS |
| 2 | Runs testMethodCompletesWithinTimeout with 2 seconds timeout | Method starts, simulates 1 second sleep | Check method finishes before 2 seconds timeout | PASS |
| 3 | Assertion assertTrue(true) executes | Method completed successfully within time | assertTrue condition is true | PASS |
| 4 | Runs testMethodExceedsTimeout with 1 second timeout | Method starts, simulates 2 seconds sleep | Check method finishes before 1 second timeout | FAIL |
| 5 | Timeout exceeded, test runner interrupts method | Method interrupted due to timeout | Timeout exceeded exception thrown | FAIL |