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

标签 java ant junit timeout junit4

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

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

最佳答案

恢复一个旧问题,因为答案没有提供示例。

你可以指定超时

  1. 根据测试方法:

     @Test(timeout = 100) // Exception: test timed out after 100 milliseconds
     public void test1() throws Exception {
         Thread.sleep(200);
     }
    
  2. 测试类中的所有方法使用 Timeout @规则:

     @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);
     }
    
  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);
     }
    
  4. 甚至对 all classes in your entire suite 应用超时(@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,因为这将为您的代码提供更多粒度。

关于java - 在 perBatch forkmode 中使用 <junit> 时设置每个测试或每个类超时的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8743594/

相关文章:

java - 颜色类别不改变颜色

java - 将/libs/*.jar打包成一个jar?

java - 哪个处理器成本最高?

java - 自定义 Ant 任务上的 "No compatible constructor"?

ant - 为自己的框架创建新的 allure 适配器

unit-testing - Db 单元测试。禁用约束

java - 用于从单向一对多关系检索数据的 Hibernate 查询

java - 数组不会通过 for 循环到达下一个位置

java - 在服务器上使用 Ant 实现自动化

java - 如何测试具有私有(private)方法、字段或内部类的类?