Assigning Priority to Test cases in TestNG

In TestNG, by default execution of the test cases is in alphabetic order. Consider a below example which has 4 test cases which are defined in random order in Java Class.

package com.qatechhub.testng.package1;

import org.testng.annotations.Test;

public class Testclass3 {
	
	
		@Test 
		public void testcase1(){
			System.out.println("Test case 1");
		}

		@Test 
		public void testcase3(){
			System.out.println("Test case 3");
		}

		@Test 
		public void testcase2(){
			System.out.println("Test case 2");
		}

		@Test 
		public void testcase4(){
			System.out.println("Test case 4");
		}

	}


Result of above Execution:

[TestNG] Running:
C:\Users\Saurabh\AppData\Local\Temp\testng-eclipse–1602420994\testng-customsuite.xml

Test case 1
Test case 2
Test case 3
Test case 4

Defining Priority of test cases:

An attribute called priority can be passed to change the priority of a test case.

Priority attribute takes integer value as an input, least the value of integer high is the priority.

Example:

package testNG;

import org.testng.annotations.Test;

public class TestNG {

	@Test (priority=2)
	public void testcase1(){
		System.out.println("Test case 1");
	}

	@Test (priority=1)
	public void testcase3(){
		System.out.println("Test case 3");
	}

	@Test (priority=4)
	public void testcase2(){
		System.out.println("Test case 2");
	}

	@Test (priority=3)
	public void testcase4(){
		System.out.println("Test case 4");
	}

}

Based on the priority set for the test cases in above code. Order of execution will be:

Test case 3
Test case 1
Test case 4
Test case 2

One tip – Generally in real time classes for priority attribute assign a value like 1000, 2000, 3000, -1000, -2000 etc, this way if a new test case comes whose priority is in between two test cases you can easily add them in between without altering other test cases.

PS: For any questions queries or comment feel free to write us at saurabh@qatechhub.com or support@qatechhub.com. Happy Learning 🙂

Saurabh Dhingra

About the Author

Saurabh Dhingra

Follow Saurabh Dhingra: