Java 什么';使用<;junit>;在perBatch模式下?

Java 什么';使用<;junit>;在perBatch模式下?,java,ant,junit,timeout,junit4,Java,Ant,Junit,Timeout,Junit4,如果任何人编写的测试运行时间超过1秒,我希望构建失败,但如果我在perTest模式下运行,则需要更长的时间 我可能会编写一个自定义任务来解析junit报告,并基于此使构建失败,但我想知道是否有人知道或能想出一个更好的选择。如果使用junit 4和@Test,可以指定timeout参数,该参数将使耗时超过指定时间的测试失败。这样做的缺点是,您必须将其添加到每个测试方法中 一个可能更好的替代方法是使用@规则。有了这个,你可以按类(甚至在共享的超级类中)来做。因为答案没有提供示例,所以重新提出一个旧问

如果任何人编写的测试运行时间超过1秒,我希望构建失败,但如果我在perTest模式下运行,则需要更长的时间


我可能会编写一个自定义任务来解析junit报告,并基于此使构建失败,但我想知道是否有人知道或能想出一个更好的选择。

如果使用junit 4和
@Test
,可以指定
timeout
参数,该参数将使耗时超过指定时间的测试失败。这样做的缺点是,您必须将其添加到每个测试方法中


一个可能更好的替代方法是使用
@规则
。有了这个,你可以按类(甚至在共享的超级类中)来做。

因为答案没有提供示例,所以重新提出一个旧问题

您可以指定超时

  • 按照试验方法:

    @Test(timeout = 100) // Exception: test timed out after 100 milliseconds
    public void test1() throws Exception {
        Thread.sleep(200);
    }
    
  • 对于使用
    超时
    @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);
    }
    
    @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);
    }
    
  • 全局获取使用静态
    超时运行类中所有测试方法的总时间
    @ClassRule

    @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);
    }
    
    @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
    )应用于:

  • 编辑: 最近不推荐使用超时来利用此初始化

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

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

    超时
    @规则
    很好。遗憾的是,您不能在
    @Suite
    上执行此操作。或者你可以?嗯。我想知道是否有一种相对简单的方法可以在运行时将@Rule添加到所有类中,而不是将@Rule添加到每个类中?@Jun DaiBates Kobashigawa-你可以像使用Junit 3一样使用自定义测试用例基类。不是很理想,但是一个不错的工作环境。很好。我很久以前就停止使用JUnit了。最后一个选项看起来不错,尽管我当时正在寻找的是一种全局暂停从Ant/Gradle运行的所有测试的方法,以便对项目中的每个测试强制执行(比如说)1秒的超时(基本上是作为在这个400人项目中工作的每个人都要处理的约束)。如果我将@Rule与espresso和Robolectric一起使用,测试将失败,因为“无法在未调用Looper.prepare()的线程内创建处理程序”