Until the introduction of @FixMethodOrder annotation Junit by design did not specify the order due the practice that well written test code could be run independently in no particular order. In version 4.11, you have the ability to change this default behavior by annotating your test class with the @FixMethodOrder. There are two options available
- @FixMethodOrder(MethodSorters.JVM): Will run unit test in the order returned by the JVM which is not predicable
- @FixMethodOrder(MethodSorters.NAME_ASCENDING): Sorts the test by method name
Order by name acending
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class SpecifyOrderOfTests {
private static String executionOrder = "";
@Test
public void c_three () {
executionOrder += "three";
}
@Test
public void a_one () {
executionOrder += "one";
}
@Test
public void b_two () {
executionOrder += "two";
}
@AfterClass
public static void validate () {
assertEquals("onetwothree", executionOrder);
}
}