0
0
JUnittesting~10 mins

assertTimeout for performance in JUnit - Test Execution Trace

Choose your learning style9 modes available
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.

Test Code - JUnit 5
JUnit
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();
        });
    }
}
Execution Trace - 7 Steps
StepActionSystem StateAssertionResult
1Test startsJUnit test runner initialized-PASS
2JUnit invokes testPerformTaskCompletesWithinOneSecond()Test method ready to execute-PASS
3assertTimeout starts timer with 1 second limitTimer running to measure execution duration-PASS
4performTask() method executes and sleeps for 500 millisecondsSimulated task running-PASS
5performTask() completes within 500 millisecondsTask finished before timeoutExecution time <= 1 secondPASS
6assertTimeout verifies execution time is within limitTest method execution completeassertTimeout passesPASS
7Test finishes successfullyJUnit reports test passed-PASS
Failure Scenario
Failing Condition: performTask() takes longer than 1 second to complete
Execution Trace Quiz - 3 Questions
Test your understanding
What does assertTimeout verify in this test?
AThe method returns the correct result
BThe method throws an exception
CThe method completes execution within the specified time limit
DThe method runs on a separate thread
Key Result
Use assertTimeout in JUnit to ensure methods complete within expected time limits, helping catch performance regressions early.