【JAVA-UT】10、ClassRule--集体的规范

文|码术张

一、ClassRule与Rule的比较

下面两个类ClassRuleTest、TimeoutTest,分别使用ClassRule、Rule,来判断两个Test方法的运行时间。

一个Test方法是should_timeout1,打印一个字母A后,睡眠2000ms。

一个Test方法是should_timeout2,打印一个字母B后,睡眠2000ms。

ClassRuleTest类:

public class ClassRuleTest {
  @ClassRule
  public  static Timeout timeout = Timeout.millis(3000);

  @Test
  public void should_timeout1() throws InterruptedException {
    System.out.println("A...");
    Thread.sleep(2000);
  }

  @Test
  public void should_timeout2() throws InterruptedException {
    System.out.println("B...");
    Thread.sleep(2000);
  }

}

运行结果为:

1541493756208.png

TimeoutTest类:

public class TimeoutTest {
  @Rule
  public TestRule timeout = Timeout.millis(3000);

  @Test
  public void should_timeout1() throws InterruptedException {
     System.out.println("A...");
     Thread.sleep(2000);
  }

  @Test
  public void should_timeout2() throws InterruptedException {
     System.out.println("B...");
     Thread.sleep(2000);
  }
}

运行结果为:

1541492955046.png

运行结果一个失败,一个成功。

为什么?

使用Rule,意味着每一个测试方法的运行时间,不能超过设置的时间,如3000ms。

使用ClassRule,则是所有测试方法的运行时间的和,不能超过3000ms。

Rule的作用范围是method-level.

ClassRule的作用范围是class level.

另外在声明上不同:

@ClassRule
public static Timeout timeout = Timeout.millis(3000);
@Rule
public TestRule timeout = Timeout.millis(3000);

使用ClassRule时,变量必须声明为public static,而使用Rule,不需要static。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,845评论 18 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,926评论 6 342
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 172,909评论 25 708
  • 趋势肤浅的原因是他只看到短期内上升下降。周期拉长了时间轴讲明白了循环往复。学习工作感情都有波动过程。长期努力,定会...
    绿禾心理咨询催眠疗愈阅读 112评论 0 1
  • 进程是怎么描述的?这是一个提纲挈领性的东西,它可以把内存管理,文件系统,信号,进程间通信等等全都串联起来 进程的描...
    那只大象阅读 3,602评论 0 6