Monday, 5 July 2021

Junit5: TestMethodOrder and Order annotations

In general, unit test are independent. One unit test is not dependent on other unit tests. But there are cases, while writing integration, system tests, order of execution of test methods may matter to you.

 

You can specify the order of test methods using @TestMethodOrder and Order annotations.

 

Example 1: Using @TestMethodOrder and Order annotation.

Annotate your test class or test interface with @TestMethodOrder and specify the desired MethodOrderer implementation. In this example, I am going to use ‘OrderAnnotation’ which execute test methods based on @Order annotation.

 

OrderedTestMethodDemo.java

package com.sample.app;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
import org.junit.jupiter.api.Order;

@TestMethodOrder(OrderAnnotation.class)
public class OrderedTestMethodDemo {

	@Test
	@Order(1)
	public void loginTest() {
		System.out.println("Executing login test");
	}

	@Test
	@Order(3)
	public void logoutTest() {
		System.out.println("Logged out Successfully!!!!");
	}

	@Test
	@Order(2)
	public void sendMoneyTest() {
		System.out.println("Transferred money");
	}

	@Test
	@Order(3)
	public void receiveReceiptTest() {
		System.out.println("Received receipt");
	}

}

 

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

Executing login test
Transferred money
Received receipt
Logged out Successfully!!!!

Example 2: Sort test methods alphanumerically.

'org.junit.jupiter.api.MethodOrderer.Alphanumeric' class is used to execute the test methods in alphanumeric order.

 

AlphaNumericOrderedTestMethodDemo.java

package com.sample.app;

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

@TestMethodOrder(Alphanumeric.class)
public class AlphaNumericOrderedTestMethodDemo {

	@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");
	}
}


When you ran above test, 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