0
0
JUnittesting~15 mins

assertTimeout for performance in JUnit - Build an Automation Script

Choose your learning style9 modes available
Verify method completes within 2 seconds using assertTimeout
Preconditions (2)
Step 1: Call the method named 'performHeavyCalculation' without parameters
Step 2: Measure the execution time of the method
Step 3: Verify that the method finishes execution within 2 seconds
✅ Expected Result: The test passes if 'performHeavyCalculation' completes within 2 seconds, otherwise it fails
Automation Requirements - JUnit 5
Assertions Needed:
Use assertTimeout to check method execution time is less than or equal to 2 seconds
Best Practices:
Use lambda expression inside assertTimeout to call the method
Avoid Thread.sleep or manual timing for performance assertion
Keep test method simple and focused on timing assertion
Automated Solution
JUnit
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.

Common Mistakes - 3 Pitfalls
Using Thread.sleep to simulate timing instead of assertTimeout
Calling the method outside the lambda passed to assertTimeout
Using assertTimeoutPreemptively without understanding it cancels the method on timeout
Bonus Challenge

Now add data-driven testing with 3 different methods that should complete within 2 seconds each

Show Hint