0
0
JUnittesting~10 mins

Timeout annotations in JUnit - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test checks that a method completes within a specified time limit using JUnit's timeout annotation. It verifies the test fails if the method runs longer than allowed.

Test Code - JUnit 5
JUnit
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.*;

public class TimeoutTest {

    @Test
    @Timeout(value = 2, unit = TimeUnit.SECONDS)
    void testMethodCompletesWithinTimeout() throws InterruptedException {
        // Simulate work that takes 1 second
        Thread.sleep(1000);
        assertTrue(true);
    }

    @Test
    @Timeout(value = 1, unit = TimeUnit.SECONDS)
    void testMethodExceedsTimeout() throws InterruptedException {
        // Simulate work that takes 2 seconds
        Thread.sleep(2000);
        assertTrue(true);
    }
}
Execution Trace - 5 Steps
StepActionSystem StateAssertionResult
1Test runner starts and loads TimeoutTest classJUnit test environment initialized-PASS
2Runs testMethodCompletesWithinTimeout with 2 seconds timeoutMethod starts, simulates 1 second sleepCheck method finishes before 2 seconds timeoutPASS
3Assertion assertTrue(true) executesMethod completed successfully within timeassertTrue condition is truePASS
4Runs testMethodExceedsTimeout with 1 second timeoutMethod starts, simulates 2 seconds sleepCheck method finishes before 1 second timeoutFAIL
5Timeout exceeded, test runner interrupts methodMethod interrupted due to timeoutTimeout exceeded exception thrownFAIL
Failure Scenario
Failing Condition: Method execution time exceeds the specified timeout value
Execution Trace Quiz - 3 Questions
Test your understanding
What causes the testMethodExceedsTimeout test to fail?
AThe method runs longer than the specified timeout
BThe assertion assertTrue(false) fails
CThe test method throws a NullPointerException
DThe test method completes instantly
Key Result
Using timeout annotations helps catch tests that hang or run too long, ensuring faster feedback and preventing stalled test suites.