If you have ready my previous post about best practices for JUnit testcases, you will find out that writing ordered testcases is considered bad practice. But, still if you caught in a situation where test case ordering is the only way out then you can use MethodSorters class. Lets see how??
MethodSorters is a new class introduced after Junit 4.6 release (please verify again). This class declared three types of execution order, which can be used in your test cases while executing them.
/** Sorts the test methods by the method name, in lexicographic order */ NAME_ASCENDING(MethodSorter.NAME_ASCENDING), /** Leaves the test methods in the order returned by the JVM. Note that the order from the JVM my vary from run to run */ JVM(null), /** Sorts the test methods in a deterministic, but not predictable, order */ DEFAULT(MethodSorter.DEFAULT);
Lets see them in action one by one.
package corejava.test.junit;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
//Running test cases in order of method names in ascending order
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class OrderedTestCasesExecution {
@Test
public void secondTest() {
System.out.println("Executing second test");
}
@Test
public void firstTest() {
System.out.println("Executing first test");
}
@Test
public void thirdTest() {
System.out.println("Executing third test");
}
}
Output:
Executing first test
Executing second test
Executing third test
Now try with JVM option.
package corejava.test.junit;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
//Running test cases in order of method names in ascending order
@FixMethodOrder(MethodSorters.JVM)
public class OrderedTestCasesExecution {
@Test
public void secondTest() {
System.out.println("Executing second test");
}
@Test
public void firstTest() {
System.out.println("Executing first test");
}
@Test
public void thirdTest() {
System.out.println("Executing third test");
}
}
Output:
Executing third test
Executing first test
Executing second test
You now have a way to execute your test cases in order, but i will still suggest you not to use this. Make each test case independent.
Happy Learning !!






Simply switch to TestNG which acknowledges the fact that test ordering SOMETIMES is essential.
Posted by tomekkaczanowski | 30 November, 2012, 2:07 PMHi Tom, Thanks for suggestion. Seems like JUNIT guys finally understood, and brought this feature in.
Posted by Lokesh Gupta | 30 November, 2012, 2:14 PM