Affi
Affi

Reputation: 152

TestNG - Running same class with multiple threads in parallel

Is there a way to run same class in parallel with multiple threads, like

<suite name="myTestSuite" verbose="1">
    <test name="myTest" parallel="classes" thread-count="5">
        <classes>
            <class name="myPackage.Test" />
        </classes>
    </test>
</suite>

I want to the class 'myPackage.Test' to be invoked in 5 parallel threads.I know that it works if I want to executed different classes in parallel, like

<suite name="myTestSuite" verbose="1">
    <test name="myTest" parallel="classes" thread-count="5">
        <classes>
            <class name="myPackage.Test1" />
            <class name="myPackage.Test2" />
            <class name="myPackage.Test3" />
            <class name="myPackage.Test4" />
            <class name="myPackage.Test5" />
        </classes>
    </test>
</suite>

Upvotes: 1

Views: 1604

Answers (2)

tim-slifer
tim-slifer

Reputation: 1088

As an alternate to the Factory pattern, you could create a <test> node for each time you want to run the class, then parallelize by test. You'd also want to move your parallelization attributes to the <suite> node. For example:

<suite name="mySuite" parallel="tests" thread-count="5">

    <test name="myTest1">
        <classes>
            <class name="myPackage.Test" />
        </classes>
    </test>

    <!-- Repeat the '<test>' node as many times as you wish to run the class -->

</suite>

You'll have to name each <test> uniquely, but this is decently simple way to run the same class many times and in parallel.

Upvotes: 2

juherr
juherr

Reputation: 5740

What you can do is using a Factory to create 5 instances of your test class.

public class TestFactory {

  @Factory
  public Object[] createInstances() {
   Object[] result = new Object[5]; 
   for (int i = 0; i < 5; i++) {
      result[i] = new Test();
    }
    return result;
  }
}

Then, you can use parallel="instances".

<suite name="myTestSuite" verbose="1">
    <test name="myTest" parallel="instances" thread-count="5">
        <classes>
            <class name="myPackage.TestFactory"/>
        </classes>
    </test>
</suite>

Upvotes: 0

Related Questions