Monday 16 March 2020

TestNG: Run test methods in parallel

You can specify number of parallel threads that execute given suite of test cases in suite definition xml file.

Example
<suite name="sanity test suite" parallel="methods" thread-count="3">

</suite>

Above snippet define 3 parallel threads to execute the test cases.

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

import org.testng.annotations.Test;

public class ParallelTestDemo1 {

  @Test
  public void a() {
    System.out.println("a is executed by : " + Thread.currentThread().getName());
  }

  @Test
  public void b() {
    System.out.println("b is executed by : " + Thread.currentThread().getName());
  }

  @Test
  public void c() {
    System.out.println("c is executed by : " + Thread.currentThread().getName());
  }

  @Test
  public void d() {
    System.out.println("d is executed by : " + Thread.currentThread().getName());
  }

  @Test
  public void e() {
    System.out.println("e is executed by : " + Thread.currentThread().getName());
  }

  @Test
  public void f() {
    System.out.println("f is executed by : " + Thread.currentThread().getName());
  }

  @Test
  public void g() {
    System.out.println("g is executed by : " + Thread.currentThread().getName());
  }

}

Define ‘ParallelDemo1.xml’ file in the same package where ‘ParallelTestDemo1.java’ is created.

ParallelDemo1.xml
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd" >

<suite name="sanity test suite" parallel="methods" thread-count="3">

  <test name="Demo test app">
    <classes>
      <class name="com.sample.app.tests.ParallelTestDemo1"></class>
    </classes>
  </test>

</suite>

How to run the suite?
Right click on suite file -> Run As -> TestNG Suite.

You will see below messages in console.

[RemoteTestNG] detected TestNG version 7.0.0
a is executed by : TestNG-test=Demo test app-1
b is executed by : TestNG-test=Demo test app-2
c is executed by : TestNG-test=Demo test app-3
e is executed by : TestNG-test=Demo test app-2
d is executed by : TestNG-test=Demo test app-3
f is executed by : TestNG-test=Demo test app-1
g is executed by : TestNG-test=Demo test app-2

===============================================
sanity test suite
Total tests run: 7, Passes: 7, Failures: 0, Skips: 0
===============================================


Previous                                                    Next                                                    Home

No comments:

Post a Comment