Use the annotation -- @FixMethodOrder(MethodSorters.DEFAULT)
. This runs all tests within the class in a deterministic and somewhat predictable order. The implementation hashes the method names and compares them. In the scenario of a tie, it sorts by lexicographical order.
Code Segment Below Taken from JUnit Github -- MethodSorter.java
public int compare(Method m1, Method m2) {
int i1 = m1.getName().hashCode();
int i2 = m2.getName().hashCode();
if(i1 != i2) {
return i1 < i2 ? -1 : 1;
}
return NAME_ASCENDING.compare(m1,m2);
}
Example
@FixMethodOrder(MethodSorters.DEFAULT)
public class OrderedTest {
@Test
public void testA() {}
@Test
public void testB() {}
@Test
public void testC() {}
}
Suppose hashes for testA
, testB
, and testC
are 3, 2, and 1 respectively. Then the execution order is
Suppose hashes for all tests are the same. Since all hashes are the same, execution order is based on lexicographical order. The execution order is