Monday, 5 July 2021

Junit5: Execute test methods in custom order

By implementing 'org.junit.jupiter.api.MethodOrderer' interface, we can specify the order of execution of test methods.

 

Step 1: Define Custom Order by implementing MethodOrderer interface.

 

MethodNameOrderer.java

package com.sample.app.util;

import java.util.Comparator;

import org.junit.jupiter.api.MethodDescriptor;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.MethodOrdererContext;

public class MethodNameOrderer implements MethodOrderer {
	@Override
	public void orderMethods(MethodOrdererContext context) {
		context.getMethodDescriptors().sort(METHOD_NAME_COMPARATOR);
	}

	private static final Comparator<MethodDescriptor> METHOD_NAME_COMPARATOR = new Comparator<MethodDescriptor>() {

		@Override
		public int compare(MethodDescriptor methodDescriptor1, MethodDescriptor methodDescriptor2) {

			return methodDescriptor1.getMethod().getName().compareTo(methodDescriptor2.getMethod().getName());

		}

	};

}

Step 2: Use ‘MethodNameOrderer’ with @TestMethodOrder annotation to execute the test methods in alphabetical order.

 

MethodNameOrdererDemo.java

package com.sample.app;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;

import com.sample.app.util.MethodNameOrderer;

@TestMethodOrder(MethodNameOrderer.class)
public class MethodNameOrdererDemo {
	@Test
	void A_1() {
		System.out.println("Executing A_1");
	}

	@Test
	void A() {
		System.out.println("Executing A");
	}

	@Test
	void D() {
		System.out.println("Executing D");
	}

	@Test
	void B() {
		System.out.println("Executing B");
	}

	@Test
	void H() {
		System.out.println("Executing H");
	}

	@Test
	void F() {
		System.out.println("Executing F");
	}

	@Test
	void C() {
		System.out.println("Executing C");
	}
}


Run MethodNameOrdererDemo class, you will see below messages in console.

Executing A
Executing A_1
Executing B
Executing C
Executing D
Executing F
Executing H


You can download complete working application from this link.

https://github.com/harikrishna553/junit5/tree/master/junit5-examples

 

  

Previous                                                    Next                                                    Home

No comments:

Post a Comment