Timeout in JUNIT

  


What is Timeout in JUnit?


Timeout in JUnit is a mechanism to fail a test automatically if it takes longer than a specified duration to complete. This is particularly useful when you're testing:

  • Long-running methods

  • Infinite loops

  • Performance-sensitive code


It helps ensure that the method finishes execution within the expected time limit, improving test reliability and performance.


Timeout in JUnit 4

In JUnit 4, timeout is specified using the @Test(timeout = X) annotation where X is in milliseconds.


Example:



import org.junit.Test;

public class TimeoutExampleJUnit4 {

    @Test(timeout = 1000) // fails if execution takes more than 1 second
    public void testWithTimeout() throws InterruptedException {
        Thread.sleep(500); // will pass
    }

    @Test(timeout = 1000)
    public void testTimeoutExceeded() throws InterruptedException {
        Thread.sleep(1500); // will fail due to timeout
    }
}




Timeout in JUnit 5

In JUnit 5, timeout is handled using the org.junit.jupiter.api.Assertions.assertTimeout() and assertTimeoutPreemptively() methods.

Methods:

  • assertTimeout(Duration, Executable) → waits for completion (may continue executing even after timeout).

  • assertTimeoutPreemptively(Duration, Executable) → aborts execution if time exceeded.


Example:



import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertTimeout;
import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;

import java.time.Duration;

public class TimeoutExampleJUnit5 {

    @Test
    void testTimeout() {
        assertTimeout(Duration.ofMillis(1000), () -> {
            Thread.sleep(500); // will pass
        });
    }

    @Test
    void testTimeoutExceeded() {
        assertTimeout(Duration.ofMillis(1000), () -> {
            Thread.sleep(1500); // will fail but finish execution
        });
    }

    @Test
    void testPreemptiveTimeoutExceeded() {
        assertTimeoutPreemptively(Duration.ofMillis(1000), () -> {
            Thread.sleep(1500); // will fail and stop execution
        });
    }
}




Difference Between assertTimeout vs assertTimeoutPreemptively


FeatureassertTimeout()assertTimeoutPreemptively()
Execution continuesYesNo
Test fails if time exceedsYesYes
Useful for code with side effectsYesNo (might terminate mid-way)