Search⌘ K

Assertion: assertTimeout()

Explore how to use JUnit 5's assertTimeout and assertTimeoutPreemptively methods to control test execution duration. Understand their differences, how they handle timeouts, and apply them in your unit tests for efficient timeout management.

The assertTimeout() method

The assertTimeout() method asserts that execution of the given Executable completes before the given timeout. The timeout value is specified as a java.time.Duration object.

There are basically three useful overloaded methods for assertTimeout:

JUnit5 v5.8
assertTimeout(Duration timeout, Executable executable)
assertTimeout(Duration timeout, Executable executable, String message)
assertTimeout(Duration timeout, Executable executable, Supplier<String>
messageSupplier)

Examples of assertTimeout()

Let’s look at some examples of the methods above:

JUnit5 v5.8
import static org.junit.jupiter.api.Assertions.assertTimeout;
import java.time.Duration;
public class TimeoutTest {
@Test
@DisplayName("Simple assertTimeout")
public void simpleTimeout()
{
assertTimeout(Duration.ofSeconds(5), () -> Thread.sleep(3000));
}
}

Note: The methods above give the same output ...