Priority in TestNG

In this section we will concentrate on Priority in TestNG. TestNG is a framework which ca n be used to perform Unit Testing, Integration Testing, Functional Testing, Regression Test etc. This support declaring multiple Test in a single class. Now one question should come to your mind that in which order the Test will be executing or how we can run the tests in particular order in single shot if all are declared inside a single class.

We can achieve this by using the Priority attribute with @Test Annotation. The value of the priority will start form 0 and continues with 1,2,3,4 —–.

0 is the highest Priority.

Example

If there is no priority declared with @Test then it will run based on the alphabetical order. Below is the example of running the Non-Prioritized Test.

Syntax:  @Test(priority =0)
import org.testng.annotations.Test;

public class testNGPriorityExample {
	@Test(priority = 1)
	public void registerUser()
	{
		System.out.println("Register your account");
	}
	@Test(priority=2)
	public void sendMail()
	{
		System.out.println("Send email after login");
	}
	@Test(priority=3)
	public void login()
	{
		System.out.println("Login to the account after registration");
	}
}

Explanation:

Here we have 3 test case. One is Register User, second is Sending Email and third is Login. In the above scenario , though we have given Register User as priority 1, Sending Mail as priority 2 and Login as priority 3, so when we will execute this test case then output will be displayed as below.

Output:

Register your account

Send email after login

Login to the account after registration

Sequence of Execution

If you have both non-priority and priority Test in a single class, then the First priority will be given the Non-Priority Test. This will execute in the alphabetical order. After that those tests will be running for which Priority is mention under @Test annotation.

Let’s understand this from below example.

Example

import org.testng.annotations.Test;

public class testNGPriorityExample {
	@Test(priority = 1)
	public void registerUser()
	{
		System.out.println("Register your account");
	}
	@Test
	public void sendMail()
	{
		System.out.println("Send email after login ");
	}
	@Test(priority=3)
	public void login()
	{
		System.out.println("Login to the account after registration");
	}
}
Output:

Send email after login

Register your account

Login to the account after registration

Explanation:

In this example we can see that sendMail() method has no priority where as registerUser() and login() has priority set. So sendMail will be executed first then other 2 method.

Now we have clear idea how to set the priority in TestNG and manage the sequence to run the test case,.

Leave a Reply

Your email address will not be published. Required fields are marked *