Ordered testcases execution in junit 4

Spread the words...Share on Google+3Share on Facebook6Tweet about this on Twitter6Share on LinkedIn7Buffer this pageShare on StumbleUpon0Share on Reddit0

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 !!

Spread the words...Share on Google+3Share on Facebook6Tweet about this on Twitter6Share on LinkedIn7Buffer this pageShare on StumbleUpon0Share on Reddit0

 

 

Give me your email address and whenever I write any tutorial or discuss any java concept, you will receive a little email in your inbox.

Join 2,865 other subscribers

6 thoughts on “Ordered testcases execution in junit 4”

Want to ask any question? Or suggest anything?