junit @test order - How do you sort the order of test cases in JUNIT?

Although writing ordered test cases is considered a bad practice. There are instances in any testing framework where even though the test cases are independent of each other you want them to run in a certain order. ( Sort the test cases )
The solution is to use MethodSorters class. MethodSorters is a new class that was introduced after Junit 4.11 release and uses three types of execution orders.
** 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);


You will require the following imports to achieve the same:
import org.junit.FixMethodOrder;
import org.junit.runners.MethodSorters;

You now have a way to execute your test cases in order :)
Happy Test Automation!

Comments

Popular posts from this blog

Software Testing @ Microsoft

Trim / Remove spaces in Xpath?