问题
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 assertTimeoutPreemptively for every test.
回答1:
You mentioned the JUnit 4 Timeout @Rule, which allows specifying timeouts on a per-test class basis. JUnit 5.5 has a direct equivalent as an experimental feature 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.
回答2:
Prior to version 5.5 of JUnit, it was not possible to enforce a global, preemptive timeout for tests in JUnit Jupiter. This functionality was added as an experimental feature to JUnit 5.5.
To view the discussion around this feature, see the following issue: https://github.com/junit-team/junit5/issues/80
回答3:
Junit 5.5 does support "global timeout". Just have a look at documentation of corresponding property knobs.
For example, try to open file src/test/resources/junit-platform.properties
and paste there:
junit.jupiter.execution.timeout.default=42 ms
来源:https://stackoverflow.com/questions/47041313/junit-5-global-timeout