在perBatch forkmode中使用<junit>时,设置每次测试或每类超时的最佳方法是什么?

Jun*_*awa 10 java ant junit timeout junit4

如果有人编写一个运行时间超过1秒的测试,我想要失败,但是如果我在perTest模式下运行它需要更长时间.

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

Mif*_*eet 15

由于答案没有提供一个例子,因此重新提出一个旧问题.

您可以指定超时

  1. 每种测试方法:

    @Test(timeout = 100) // Exception: test timed out after 100 milliseconds
    public void test1() throws Exception {
        Thread.sleep(200);
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 对于测试类中的所有方法,使用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);
    }
    
    Run Code Online (Sandbox Code Playgroud)
  3. 全局使用静态运行类中所有测试方法的总时间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);
    }
    
    Run Code Online (Sandbox Code Playgroud)
  4. 甚至对整个套件中的所有类应用超时(@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);
    }
    
    Run Code Online (Sandbox Code Playgroud)

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

@Rule
public Timeout timeout = new Timeout(120000, TimeUnit.MILLISECONDS);
Run Code Online (Sandbox Code Playgroud)

您现在应该提供Timeunit,因为这将为您的代码提供更多粒度.


ftr*_*ftr 7

如果使用JUnit 4 @Test,则可以指定使timeout测试时间超过指定时间的参数失败的参数.缺点是你必须将它添加到每个测试方法中.

一个可能更好的选择是使用@Rulewith org.junit.rules.Timeout.有了这个,你可以按类(甚至在共享的超类)中完成.