使用时设置每个测试或每个类超时的最佳方法是什么?在 perBatch fork 模式下?
如果有人编写了一个运行时间超过 1 秒的测试,我希望构建失败,但如果我在 perTest 模式下运行,则需要更长的时间。
我可能可以编写一个自定义任务来解析 junit 报告并基于该报告使构建失败,但我想知道是否有人知道或能想到更好的选择。
I want to fail the build if anyone writes a test that takes longer than 1 second to run, but if I run in perTest mode it takes much, much longer.
I could probably write a custom task that parses the junit reports and fails the build based on that, but I was wondering if anyone knows or can think of a better option.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
由于答案没有提供示例,因此重新提出一个老问题。
您可以指定超时
每个测试方法:
对于使用 的测试类中的所有方法
超时
@Rule
:<前><代码> @Rule
公共超时超时=新超时(100);
@Test // 异常:测试在 100 毫秒后超时
公共无效方法超时()抛出异常{
线程.sleep(200);
}
@测试
公共无效methodInTime()抛出异常{
线程.sleep(50);
}
使用静态
Timeout
全局运行类中所有测试方法的总时间@ClassRule
:<前><代码>@ClassRule
公共静态超时 classTimeout = new Timeout(200);
@测试
公共无效test1()抛出异常{
线程睡眠(150);
}
@Test // InterruptedException:睡眠中断
公共无效test2()抛出异常{
线程睡眠(100);
}
甚至应用超时(
@Rule
) code> 或@ClassRule
)到整个套件中的所有类:<前><代码> @RunWith(Suite.class)
@SuiteClasses({ Test1.class, Test2.class})
公共类 SuiteWithTimeout {
@ClassRule
公共静态超时 classTimeout = new Timeout(1000);
@规则
公共超时超时=新超时(100);
}
编辑:
最近已弃用 timeout 以利用此初始化。
您现在应该提供 Timeunit,因为这将为您的代码提供更多粒度。
Reviving an old question since the answer doesn't provide an example.
You can specify timeout
Per test method:
For all methods in a test class using
Timeout
@Rule
:Globally for the total time to run all test methods in the class using a static
Timeout
@ClassRule
:And even apply timeout (either
@Rule
or@ClassRule
) to all classes in your entire suite:EDIT:
timeout was deprecated recently to utilize this initialization
You should provide the Timeunit now, as this will provide more granularity to your code.
如果您使用 JUnit 4 和
@Test
,则可以指定timeout
参数,该参数将使花费时间超过指定时间的测试失败。这样做的缺点是您必须将其添加到每个测试方法中。一个可能更好的选择是使用
@Rule
和org.junit.rules.Timeout
。这样,您可以在每个类中(甚至在共享的超类中)执行此操作。If you use JUnit 4 and
@Test
, you can specifiy thetimeout
parameter that will fail a tests that's taking longer than specified. Downside for that is that you'd have to add it to every test method.A probably better alternative is the use of a
@Rule
withorg.junit.rules.Timeout
. With this, you can do it per class (or even in a shared super class).我从标签中知道这个问题是针对 JUnit 4 的,但在 JUnit 5 (Jupiter) 中,机制已更改。
来自指南:
(
unit
默认为秒,因此您可以只使用@Timeout(1)
。)在整个类中应用一次很容易:
出于您的目的,您甚至可以在构建作业中尝试顶级配置:
I know from the tags that this question was aimed at JUnit 4, but in JUnit 5 (Jupiter), the mechanism has changed.
From the guide:
(The
unit
defaults to seconds, so you could just use@Timeout(1)
.)It's easy to apply once across a class:
For your purposes, you might even experiment with top-level configuration on your build jobs: