0
0
JUnittesting~15 mins

Timeout annotations in JUnit - Build an Automation Script

Choose your learning style9 modes available
Verify that a test method fails if it exceeds the specified timeout
Preconditions (2)
Step 1: Annotate the test method with @Timeout(2) to set a 2-second timeout
Step 2: Inside the test method, add a delay of 3 seconds using Thread.sleep(3000)
Step 3: Run the test method
Step 4: Observe the test result
✅ Expected Result: The test fails due to exceeding the 2-second timeout
Automation Requirements - JUnit 5
Assertions Needed:
Verify that the test fails when execution time exceeds the timeout
Best Practices:
Use @Timeout annotation on test methods
Avoid using Thread.sleep in production code; only for testing delays
Keep timeout values reasonable to avoid flaky tests
Automated Solution
JUnit
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import java.util.concurrent.TimeUnit;

public class TimeoutTest {

    @Test
    @Timeout(value = 2, unit = TimeUnit.SECONDS)
    void testTimeoutExceeded() throws InterruptedException {
        // Simulate long running task
        Thread.sleep(3000); // 3 seconds sleep
    }
}

The test method testTimeoutExceeded is annotated with @Timeout(2 seconds). This means JUnit will fail the test if it runs longer than 2 seconds.

Inside the test, Thread.sleep(3000) pauses execution for 3 seconds, which exceeds the timeout.

When running this test, JUnit detects the timeout breach and fails the test automatically.

This example shows how to use the @Timeout annotation to prevent tests from running too long.

Common Mistakes - 3 Pitfalls
{'mistake': 'Not specifying the time unit in @Timeout annotation', 'why_bad': 'JUnit defaults to seconds, but this can cause confusion or errors if the developer expects milliseconds', 'correct_approach': "Always specify the time unit explicitly using the 'unit' parameter, e.g., @Timeout(value = 2, unit = TimeUnit.SECONDS)"}
Using Thread.sleep with a duration shorter than the timeout
Using @Timeout on non-test methods or setup methods
Bonus Challenge

Now add data-driven testing with 3 different timeout values and corresponding sleep durations to verify timeout behavior

Show Hint