【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。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值