Prioritizing of Test Cases in TestNG

In the previous post, we have seen the sequence of annotation execution. In this post, we will learn about Prioritizing of Test Cases in TestNG.

This is obvious in testing that we have multiple test cases to execute. In Selenium , can we put multiple tests under the same class? Yes, it is possible. You can use @Test annotation to put multiple test cases into the same class. Let’s see how.

Code for multiple tests under the same class in testNG:

Note: You can directly write annotation above method and it will prompt you to import its class. This is another way to create a TestNG class.

Import Annotations

import org.testng.annotations.Test;

public class PriorityExample {

	@Test
	public void TestOne(){
		System.out.println("This is Test1.");
	}
	
	@Test
	public void TestTwo(){
		System.out.println("This is Test2.");
	}
	
	@Test
	public void TestThree(){
		System.out.println("This is Test3.");
	}
	
	@Test
	public void TestFour(){
		System.out.println("This is Test4.");
	}
}

Run this class as TestNg test as shown below.

Run testNG

 

Output: You will get the output as shown below.

TestNG output multiple tests

Attention

If you will observe the output, it is not executed in the sequence as mentioned in the class. Because by default, methods annotated by @Test are executed alphabetically.

 

What is the solution for this?

TestNG provides a way to prioritize the tests to maintain the sequence as it should be executed.

prioritization In testNG

Prioritizing the methods in above class:

For prioritizing the methods , we use ‘priority‘ parameter. Parameters are keywords that can modify the annotation’s default function. Priority starts from 0. It can be put with @Test annotation above any method as shown in the program below.

import org.testng.annotations.Test;

public class PriorityExample {

	@Test(priority=0)
	public void TestOne(){
		System.out.println("This is Test1.");
	}
	
	@Test(priority=1)
	public void TestTwo(){
		System.out.println("This is Test2.");
	}
	
	@Test(priority=2)
	public void TestThree(){
		System.out.println("This is Test3.");
	}
	
	@Test(priority=3)
	public void TestFour(){
		System.out.println("This is Test4.");
	}
}

Output: You can observe the output below. It has been executed in the right order as it is mentioned in the class.

Priority test cases in testng


This is box title
Have any question or suggestion for us?Please feel free to post in Q&A Forum
Avatar photo

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...