如果有人编写的测试运行时间超过1秒,我希望构建失败,但如果我在perTest模式下运行,则需要更长的时间。
我可能会编写一个自定义任务来解析junit报告,并在此基础上使构建失败,但我想知道是否有人知道或能想到更好的选择。
由于答案没有提供示例,因此重新提出一个旧问题。
您可以指定超时
-
每个测试方法:
@Test(timeout = 100) // Exception: test timed out after 100 milliseconds public void test1() throws Exception { Thread.sleep(200); }
-
对于使用
Timeout
@Rule
:的测试类中的所有方法@Rule public Timeout timeout = new Timeout(100); @Test // Exception: test timed out after 100 milliseconds public void methodTimeout() throws Exception { Thread.sleep(200); } @Test public void methodInTime() throws Exception { Thread.sleep(50); }
-
全局使用静态
Timeout
@ClassRule
:运行类中所有测试方法的总时间@ClassRule public static Timeout classTimeout = new Timeout(200); @Test public void test1() throws Exception { Thread.sleep(150); } @Test // InterruptedException: sleep interrupted public void test2() throws Exception { Thread.sleep(100); }
-
甚至将超时(
@Rule
或@ClassRule
)应用于整个套件中的所有类:@RunWith(Suite.class) @SuiteClasses({ Test1.class, Test2.class}) public class SuiteWithTimeout { @ClassRule public static Timeout classTimeout = new Timeout(1000); @Rule public Timeout timeout = new Timeout(100); }
编辑:最近不赞成使用此初始化的超时
@Rule
public Timeout timeout = new Timeout(120000, TimeUnit.MILLISECONDS);
您现在应该提供Timeunit,因为这将为您的代码提供更多的粒度。
如果您使用JUnit 4和@Test
,您可以指定timeout
参数,该参数将使比指定时间更长的测试失败。不利的一面是,你必须把它添加到每一种测试方法中。
一个可能更好的替代方案是将@Rule
与org.junit.rules.Timeout
一起使用。有了这个,您可以按类(甚至在共享的超级类中)进行操作。
我从标签中知道这个问题是针对JUnit 4的,但在JUnit 5(Jupiter)中,机制发生了变化。
来自指南:
@Test @Timeout(value = 500, unit = TimeUnit.MILLISECONDS) void failsIfExecutionTimeExceeds500Milliseconds() { // fails if execution time exceeds 500 milliseconds }
(unit
默认为秒,所以您可以只使用@Timeout(1)
。)
跨类应用一次很容易:
要将相同的超时应用于测试类及其所有@Nested类中的所有测试方法,可以在类级别声明@timeout注释。
出于您的目的,您甚至可以在构建作业上尝试顶级配置:
"junit.jupiter.execution.timeout.test.method.default
@Test methods 的默认超时