Issue
In JUnit 5, what is the best way to enforce a global timeout for all tests?
I see that JUnit 4 has a @Rule
feature, but this has been removed in JUnit 5. And I would prefer not to have to copy-paste href="https://junit.org/junit5/docs/current/api/org.junit.jupiter.api/org/junit/jupiter/api/Assertions.html#assertTimeoutPreemptively(java.time.Duration,org.junit.jupiter.api.function.Executable)" rel="nofollow noreferrer">assertTimeoutPreemptively
for every test.
Solution
You mentioned the JUnit 4 Timeout
@Rule
, which allows specifying timeouts on a per-test class basis. JUnit 5.5 has a direct equivalent in the @Timeout
annotation. This can be applied to the class level in the same manner as the JUnit 4 rule, in which case it applies to all tests within the class and its @Nested
classes. It can also be applied to individual @Test
or lifecycle (@BeforeAll
, @BeforeEach
, @AfterEach
, or @AfterAll
) methods.
Per the JUnit 5 user guide:
The
@Timeout
annotation allows one to declare that a test, test factory, test template, or lifecycle method should fail if its execution time exceeds a given duration. The time unit for the duration defaults to seconds but is configurable.[...]
To apply the same timeout to all test methods within a test class and all of its
@Nested
classes, you can declare the@Timeout
annotation at the class level. It will then be applied to all test, test factory, and test template methods within that class and its@Nested
classes unless overridden by a@Timeout
annotation on a specific method or@Nested
class. Please note that@Timeout
annotations declared at the class level are not applied to lifecycle methods.
Answered By - M. Justin
Answer Checked By - Pedro (JavaFixing Volunteer)