0
0
JUnittesting~5 mins

Timeout annotations in JUnit

Choose your learning style9 modes available
Introduction

Timeout annotations help stop tests that take too long. This keeps your testing fast and reliable.

When a test might hang or run forever by mistake.
To make sure slow tests fail quickly instead of waiting too long.
When testing code that should finish within a certain time limit.
To avoid blocking other tests in a large test suite.
When you want to detect performance problems early.
Syntax
JUnit
@Test
@Timeout(value = 5, unit = TimeUnit.SECONDS)
public void testMethod() {
    // test code here
}

The @Timeout annotation sets a time limit for the test method.

If the test runs longer than the limit, it fails automatically.

Examples
This test fails if it runs longer than 2 seconds.
JUnit
@Test
@Timeout(value = 2, unit = TimeUnit.SECONDS)
public void quickTest() {
    // test that must finish within 2 seconds
}
Timeout defaults to seconds if unit is not specified.
JUnit
@Test
@Timeout(1)
public void defaultUnitTest() {
    // test with 1 second timeout (default unit is seconds)
}
Timeout can be set in milliseconds for very fast tests.
JUnit
@Test
@Timeout(value = 500, unit = TimeUnit.MILLISECONDS)
public void fastTest() {
    // test must finish within 500 milliseconds
}
Sample Program

The first test sleeps 1 second and passes because it is under the 2-second timeout.

The second test sleeps 2 seconds but has a 1-second timeout, so it fails.

JUnit
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import java.util.concurrent.TimeUnit;

public class TimeoutExampleTest {

    @Test
    @Timeout(value = 2, unit = TimeUnit.SECONDS)
    public void testFastMethod() throws InterruptedException {
        Thread.sleep(1000); // sleeps 1 second, should pass
    }

    @Test
    @Timeout(value = 1, unit = TimeUnit.SECONDS)
    public void testSlowMethod() throws InterruptedException {
        Thread.sleep(2000); // sleeps 2 seconds, should fail
    }
}
OutputSuccess
Important Notes

@Timeout can be used on test methods as well as @BeforeEach, @AfterEach, @BeforeAll, and @AfterAll methods.

Use timeouts carefully to avoid false failures on slow machines.

You can also set timeouts globally for all tests in some JUnit configurations.

Summary

Timeout annotations stop tests that run too long.

They help keep tests fast and catch hanging code.

Set time limits using @Timeout with a value and time unit.