当在perBatch fork模式下使用时,设置每个测试或每个类超时的最佳方法是什么< junit>?

50few1ms  于 2022-11-11  发布在  其他
关注(0)|答案(3)|浏览(140)

如果有人编写了一个运行时间超过1秒的测试,我希望构建失败,但如果我在perTest模式下运行,它需要更长的时间。
我可能会编写一个自定义任务来解析junit报告,并在此基础上使构建失败,但我想知道是否有人知道或能想到更好的选择。

ujv3wf0j

ujv3wf0j1#

因为答案没有提供例子,所以重提一个老问题。
您可以指定超时
1.根据试验方法:

@Test(timeout = 100) // Exception: test timed out after 100 milliseconds
 public void test1() throws Exception {
     Thread.sleep(200);
 }

1.对于使用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);
 }

1.使用静态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);
 }

1.甚至将超时(@Rule@ClassRule)应用于all classes in your entire suite

@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);
 }

EDIT:最近不赞成使用超时来使用此初始化

@Rule
public Timeout timeout = new Timeout(120000, TimeUnit.MILLISECONDS);

您现在应该提供时间单位,因为这将为您的代码提供更多的粒度。

xmd2e60i

xmd2e60i2#

如果您使用JUnit 4和@Test,您可以指定timeout参数,该参数将使花费时间比指定时间更长的测试失败。
一个可能更好的替代方法是使用@Ruleorg.junit.rules.Timeout。这样,您可以针对每个类(甚至在共享超类中)执行此操作。

sz81bmfz

sz81bmfz3#

我从标签中知道这个问题是针对JUnit 4的,但是在JUnit 5(Jupiter)中,mechanism has changed
来自指南:

@Test
   @Timeout(value = 500, unit = TimeUnit.MILLISECONDS)
   void failsIfExecutionTimeExceeds500Milliseconds() {
       // fails if execution time exceeds 500 milliseconds
   }

(The unit的默认值为秒,因此您可以直接使用@Timeout(1)。)
很容易在整个课程中应用一次:
要将相同的超时应用于测试类及其所有@Nested类中的所有测试方法,可以在类级别声明@Timeout注解。
出于您的目的,您甚至可以在构建作业上试验顶级配置:
“junit.jupiter.执行.超时.测试.方法.默认值”
@测试方法的默认超时

相关问题