Sunday, 15 March 2020

TestNG: Prioritize test methods execution order

By default test methods execute in alphabetical order of method names.

TestPriority.java
package com.sample.app.tests;

import org.testng.annotations.Test;

public class TestPriority {

 @Test
 public void A() {
  System.out.println("Inside A");
 }

 @Test
 public void B() {
  System.out.println("Inside B");
 }

 @Test
 public void C() {
  System.out.println("Inside C");
 }

 @Test
 public void D() {
  System.out.println("Inside D");
 }

 @Test
 public void E() {
  System.out.println("Inside E");
 }
}

When you ran TestPriority.java, you will see below messages in console.
[RemoteTestNG] detected TestNG version 7.0.0
Inside A
Inside B
Inside C
Inside D
Inside E
PASSED: A
PASSED: B
PASSED: C
PASSED: D
PASSED: E

===============================================
    Default test
    Tests run: 5, Failures: 0, Skips: 0
===============================================


===============================================
Default suite
Total tests run: 5, Passes: 5, Failures: 0, Skips: 0
===============================================

As you see the console messages, methods are executed in the order A -> B -> C -> D -> E.

How can I execute the methods in the order B -> D -> A -> C -> E?
By prioritizing the methods order of execution, you can execute the methods in the order you want.

@Test(priority = 3)
public void C() {
         System.out.println("Inside C");
}

Lower priorities will be scheduled first. If you do not specify the priority, then it is set to 0 by default.

TestPriority.java
package com.sample.app.tests;

import org.testng.annotations.Test;

public class TestPriority {

 @Test(priority = 2)
 public void A() {
  System.out.println("Inside A");
 }

 @Test
 public void B() {
  System.out.println("Inside B");
 }

 @Test(priority = 3)
 public void C() {
  System.out.println("Inside C");
 }

 @Test(priority = 1)
 public void D() {
  System.out.println("Inside D");
 }

 @Test(priority = 4)
 public void E() {
  System.out.println("Inside E");
 }
}

Run TestPriority.java, you will see below messages in console.

[RemoteTestNG] detected TestNG version 7.0.0
Inside B
Inside D
Inside A
Inside C
Inside E
PASSED: B
PASSED: D
PASSED: A
PASSED: C
PASSED: E

===============================================
    Default test
    Tests run: 5, Failures: 0, Skips: 0
===============================================


===============================================
Default suite
Total tests run: 5, Passes: 5, Failures: 0, Skips: 0
===============================================





Previous                                                    Next                                                    Home

No comments:

Post a Comment