//
you're reading...

Junit

Ordered testcases execution in junit 4

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

Discussion

2 Responses to “Ordered testcases execution in junit 4”

  1. Simply switch to TestNG which acknowledges the fact that test ordering SOMETIMES is essential.

    Posted by tomekkaczanowski | 30 November, 2012, 2:07 PM

Leave a comment

Enter your email address to receive notifications of new posts by email.

  • Latest Updates

    • Reading/writing excel files in java : POI tutorial ... 15 hours ago
    • Popular HashMap and ConcurrentHashMap interview questions ... 5 days ago
    • 8 signs of bad unit test cases ... 1 week ago
    • 5 class design principles [S.O.L.I.D.] in java ... 1 week ago

Copyright Information