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测试方法