Test Overview
This test checks if a method completes its execution within a specified time limit using assertTimeout in JUnit. It verifies the performance by ensuring the method does not exceed the allowed duration.
This test checks if a method completes its execution within a specified time limit using assertTimeout in JUnit. It verifies the performance by ensuring the method does not exceed the allowed duration.
import static org.junit.jupiter.api.Assertions.assertTimeout; import java.time.Duration; import org.junit.jupiter.api.Test; public class PerformanceTest { public void performTask() { // Simulate a task that takes some time try { Thread.sleep(500); // 500 milliseconds } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } @Test public void testPerformTaskCompletesWithinOneSecond() { assertTimeout(Duration.ofSeconds(1), () -> { performTask(); }); } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts | JUnit test runner initialized | — | PASS |
| 2 | JUnit invokes testPerformTaskCompletesWithinOneSecond() | Test method ready to execute | — | PASS |
| 3 | assertTimeout starts timer with 1 second limit | Timer running to measure execution duration | — | PASS |
| 4 | performTask() method executes and sleeps for 500 milliseconds | Simulated task running | — | PASS |
| 5 | performTask() completes within 500 milliseconds | Task finished before timeout | Execution time <= 1 second | PASS |
| 6 | assertTimeout verifies execution time is within limit | Test method execution complete | assertTimeout passes | PASS |
| 7 | Test finishes successfully | JUnit reports test passed | — | PASS |
assertTimeout in JUnit testing?assertTimeoutassertTimeout is used to ensure that a piece of code completes within a given time limit.assertTimeout focuses on performance timing.assertTimeout in JUnit 5 to test a method processData() with a 2-second limit?Duration.ofSeconds(2) to specify 2 seconds.() -> processData().assertTimeout(Duration.ofMillis(500), () -> {
Thread.sleep(300);
Thread.sleep(250);
});assertTimeout:
assertTimeout(Duration.ofSeconds(1), processData());
processData() is called immediately, not deferred by lambda.calculate() that sometimes takes longer but should not exceed 3 seconds. Which approach correctly uses assertTimeout to fail the test if calculate() exceeds 3 seconds, and also returns the method's result for further checks?calculate() result, lambda must return it and assign to a variable.result, matching requirements.Pass the test and this pattern moves unknown