直到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 {@Testpublic void b_test_1() {System.out.println('b_test_1 called..');}@Testpublic void r_test_2() {System.out.println('r_test_2 called..');}@Testpublic void z_test_3() {System.out.println('z_test_3 called..');}@Testpublic 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