junit测试方法_JUnit测试方法订购

junit测试方法

直到版本4.10为止的Junit都使用反射API返回的测试类中测试方法的顺序作为测试方法执行的顺序– Class.getMethods() 。 引用getMethods()api的Javadoc:

返回的数组中的元素未排序,并且没有任何特定顺序。

因此,测试类中测试方法执行的顺序是不可预测的。 这在某种程度上是一个好习惯,因为它鼓励我们作为开发人员的开发人员编写可以独立存在并且不依赖于测试方法执行顺序的测试方法。

在Junit版本4.11中,测试方法执行的顺序不再那么不可预测,默认情况下,尽管未指定,但每次运行的顺序都是确定的。 通过向具有以下值的测试类添加新的@FixMethodOrder注释,可以进一步执行该顺序:

1. @FixMethodOrder(MethodSorters.DEFAULT)–基于内部比较器的确定性顺序

2. @FixMethodOrder(MethodSorters.NAME_ASCENDING)–方法名称的升序

3. @FixMethodOrder(MethodSorters.JVM)–依赖于基于反射的顺序的4.11之前的方式

考虑以下测试案例:

public class ATest {
 @Test
 public void b_test_1() {
  System.out.println('b_test_1 called..');
 }

 @Test
 public void r_test_2() {
  System.out.println('r_test_2 called..');
 }

 @Test
 public void z_test_3() {
  System.out.println('z_test_3 called..');
 }

 @Test
 public void l_test_4() {
  System.out.println('l_test_4 called..');
 }
}

4.11之前的版本运行此测试将在我的机器上打印以下内容

Running testorder.ATest
r_test_2 called..
z_test_3 called..
b_test_1 called..
l_test_4 called..

使用NAME_ASCENDING:

@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class ATest

这是输出:

Running testorder.ATest
b_test_1 called..
l_test_4 called..
r_test_2 called..
z_test_3 called..

仍然没有办法明确指定其他自定义排序方法,因为提供可预测的顺序的目的仅仅是为了使它可预测,而不是使用它来添加测试方法之间的依赖关系,因此这是很好的方法。

资源:

JUnit Wiki – https://github.com/KentBeck/junit/wiki/Test-execution-order

参考:all和杂物博客上从我们的JCG合作伙伴 Biju Kunjummen 订购JUnit测试方法

翻译自: https://www.javacodegeeks.com/2013/01/junit-test-method-ordering.html

junit测试方法

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值