Verify method completes within 2 seconds using assertTimeout
Preconditions (2)
✅ Expected Result: The test passes if 'performHeavyCalculation' completes within 2 seconds, otherwise it fails
import static org.junit.jupiter.api.Assertions.assertTimeout; import java.time.Duration; import org.junit.jupiter.api.Test; public class PerformanceTest { // Example method to test public void performHeavyCalculation() { // Simulate some work for (int i = 0; i < 1_000_000; i++) { Math.sqrt(i); } } @Test public void testPerformHeavyCalculationCompletesWithinTwoSeconds() { assertTimeout(Duration.ofSeconds(2), () -> { performHeavyCalculation(); }); } }
This test uses JUnit 5's assertTimeout method to check that performHeavyCalculation finishes within 2 seconds.
The Duration.ofSeconds(2) sets the maximum allowed time.
The method call is wrapped in a lambda expression, which assertTimeout runs and measures.
If the method takes longer than 2 seconds, the test fails automatically.
This approach is simple, readable, and uses JUnit's built-in timing features without manual timers.
Now add data-driven testing with 3 different methods that should complete within 2 seconds each
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