What is the order of execution of tests in TestNG?


A TestNG class can have different tests like test1, test2, test3, etc. Once a user runs a TestNG class consisting of various tests, it runs the test cases in an alphabetic order based on the name provided. However, the user can assign the priority to these tests so that these tests can run as per user's priority. Priority starts from 0 (highest priority) and gradually decreases as we move to 1, 2, 3, etc.

Default Order

TestNG executes different tests alphabetically. By default, test1 will run first and after that test2 and finally test3. By default, TestNG assigns priority as 0 to all tests if priority is not defined by the user. Since all tests are having same priority, it executes in an alphabetic order.

Approach/Algorithm to solve this problem

  • Step 1 − Import org.testng.annotations.Test for TestNG.

  • Step 2 − Write an annotation as @test

  • Step 3 − Repeat the steps for test2 and test3.

  • Step 4 − Repeat the steps for test2 and test3.

  • Step 5 − Now create the testNG.xml as given below.

  • Step 6 − Now, run the testNG.xml or directly testNG class in IDE or compile and run it using command line.

Example

The following code creates a TestNG class and displays its default order of execution −

import org.testng.annotations.Test;
public class OrderofTestExecutionInTestNG {
   @Test
   public void test1() {
      System.out.println("Starting execution of TEST1");
   }
   @Test
   public void test2() {
      System.out.println("Starting execution of TEST2");
   }
   @Test
   public void test3() {
      System.out.println("Starting execution of TEST3");
   }
}

testng.xml

This is a configuration file that is used to organize and run the TestNG test cases. It is very handy when limited tests are needed to execute rather than the full suite.

<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >

<suite name = "Suite1">
   <test name = "test1">
      <classes>
         <class name = "OrderofTestExecutionInTestNG"/>
      </classes>
   </test>
</suite>

Output

Starting execution of TEST1
Starting execution of TEST2
Starting execution of TEST3

Updated on: 12-Jan-2022

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements