JUnit Ordered Test Execution Example

Writing JUnit ordered test cases 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.

1. JUnit MethodSorters

MethodSorters was introduced since JUnit 4.11 release. This class declared three types of execution order, which can be used in your test cases while executing them.

  1. MethodSorters.DEFAULT – Sorts the test methods in a deterministic, but not predictable, order.
  2. MethodSorters.JVM – Leaves the test methods in the order returned by the JVM.
  3. MethodSorters.NAME_ASCENDINGSorts the test methods by the method name, in lexicographic order, with Method.toString() used as a tiebreaker.

2. JUnit Ordered Tests Example – NAME_ASCENDING

Lets see how ordered tests are written and executed in 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");
	}
}

Program Output.

Executing first test
Executing second test
Executing third test

2. JUnit Ordered Tests Example – JVM

Now execute same tests 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");
	}
}

Program Output.

Executing third test
Executing first test
Executing second test

Clearly, only NAME_ASCENDING order gives you control on true ordering and other two options do not give enough predictability in test execution order sequence for developers.

In this JUnit tutorial, we learned to write JUnit sequential tests. Let me know of your thoughts.

Happy Learning !!

Reference:

MethodSorters Class

Leave a Reply

8 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.

Our Blogs

REST API Tutorial