0
0
JUnittesting~10 mins

Test execution time analysis in JUnit - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test measures how long a simple method takes to execute and verifies that it completes within a set time limit.

Test Code - JUnit 5
JUnit
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertTimeout;
import java.time.Duration;

public class ExecutionTimeTest {

    @Test
    public void testMethodExecutionTime() throws InterruptedException {
        assertTimeout(Duration.ofMillis(500), () -> {
            // Simulate some work with sleep
            Thread.sleep(300);
        });
    }
}
Execution Trace - 6 Steps
StepActionSystem StateAssertionResult
1Test startsJUnit test runner initialized-PASS
2JUnit invokes testMethodExecutionTime()Inside test method-PASS
3assertTimeout starts timer and runs lambdaTimer running, lambda executing-PASS
4Lambda executes Thread.sleep(300) to simulate workThread sleeping for 300 milliseconds-PASS
5Lambda completes, assertTimeout checks elapsed timeElapsed time measuredElapsed time <= 500 millisecondsPASS
6Test finishes successfully within time limitTest passedTest execution time is acceptablePASS
Failure Scenario
Failing Condition: The simulated work takes longer than 500 milliseconds
Execution Trace Quiz - 3 Questions
Test your understanding
What does assertTimeout verify in this test?
AThat the code finishes within the specified time limit
BThat the code throws an exception
CThat the code returns a specific value
DThat the code runs on a separate thread
Key Result
Use assertTimeout to catch slow code early and keep tests fast and reliable.