在JUnit 5中,对所有测试强制执行全局超时的最佳方法是什么?
In JUnit 5, what is the best way to enforce a global timeout for all tests?
我看到JUnit 4具有@Rule功能,但是在JUnit 5中已将其删除.我希望不必复制粘贴 assertTimeoutPreemptively 用于每个测试.
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.
推荐答案您提到了JUnit 4 Timeout @Rule ,它允许在每个测试类的基础上指定超时. JUnit 5.5在 @Timeout 批注.可以按照与JUnit 4规则相同的方式将其应用于类级别,在这种情况下,它适用于该类及其@Nested类中的所有测试.它也可以应用于单独的@Test或生命周期(@BeforeAll,@BeforeEach,@AfterEach或@AfterAll)方法.
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.
根据 JUnit 5用户指南:
通过@Timeout批注,可以声明如果执行时间超过给定的持续时间,则测试,测试工厂,测试模板或生命周期方法应失败.持续时间的时间单位默认为秒,但可以配置.
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.
[...]
要将相同的超时应用于测试类及其所有@Nested类中的所有测试方法,可以在类级别声明@Timeout批注.然后,它将被应用于该类及其@Nested类中的所有测试,测试工厂和测试模板方法,除非被特定方法或@Nested类上的@Timeout注释覆盖.请注意,在类级别声明的@Timeout注释不适用于生命周期方法.
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.
更多推荐
JUnit 5
发布评论