JUnit 5 @Timeout Annotation
JUnit 5 @Timeout Annotation
In JUnit 5, the Timeout Test feature is used to ensure that a test completes within a specified time limit. If the test takes longer than the defined duration, it will fail automatically. This is useful for detecting performance issues or infinite loops.
Why Use Timeout?
- To prevent tests from running indefinitely.
- To detect performance bottlenecks.
- To ensure your application responds within acceptable time limits.
JUnit 5 Syntax
@Test
@Timeout(value = 2, unit = TimeUnit.SECONDS)
void testMethod() {
// your test code
}
Example
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import java.util.concurrent.TimeUnit;
import static java.lang.Thread.sleep;
public class TimeoutExampleTest {
@Test
@Timeout(value = 2, unit = TimeUnit.SECONDS)
void shouldCompleteWithinTwoSeconds() throws InterruptedException {
// Simulate a task that takes 1 second
sleep(1000);
}
@Test
@Timeout(value = 1, unit = TimeUnit.SECONDS)
void shouldFailDueToTimeout() throws InterruptedException {
// Simulate a task that takes 2 seconds
sleep(2000);
}
}
Explanation
shouldCompleteWithinTwoSeconds
– This test will pass because it completes within the timeout limit.shouldFailDueToTimeout
– This test will fail because it exceeds the 1-second timeout.
Remember to import the @Timeout
annotation from org.junit.jupiter.api.Timeout
.