When parallelizings tests using testNG, tests in a class do not get executed in the same thread

testng.xml:

<suite name="Default Suite" parallel="classes" thread-count="3">
    <test name="example">
        <classes>
            <class name="ExampleTest"/>
            <class name="ExampleTest2"/>
        </classes>
    </test>
</suite>

test :

@Test(singleThreaded = true)
public class ExampleTest {

@Test
public void firstTest() {
    // first test
}

@Test(dependsOnMethods = "firstTest")
public void secondTest() {
    // second test depends from first test
}
}

tests run in three Threads, but the first test is in one thread, and the second in the second, respectively, the second one drops as it depends on the first one. How to run parallel tests such that all tests in one class are executed in one thread ?

Thank you in advance.

Upvotes: 2

Views: 770

Answers (1)

Andrey Kotov
Andrey Kotov

Reputation: 1414

There was a bug in TestNG. Here is a link to GitHub issue.

Starting from 7.0.0-beta1 it is fixed. But you should set -Dtestng.thread.affinity=true as JVM argument. IntelliJ IDEA steps: go to Run -> Edit Configurations:

dtestng.thread.affinity=true testng dependsOnMethods

TestClass1:

import org.testng.annotations.Test;
import org.testng.log4testng.Logger;

public class TestClass1 {
    private static final Logger LOGGER = Logger.getLogger(TestClass1.class);

    @Test
    public void test1() {
        LOGGER.warn("TestClass1 - test1. Thread " + Thread.currentThread().getId());
    }

    @Test(dependsOnMethods = "test1")
    public void test2() {
        LOGGER.warn("TestClass1 - test2. Thread " + Thread.currentThread().getId());
    }
}

TestClass2:

public class TestClass2 {
    private static final Logger LOGGER = Logger.getLogger(TestClass1.class);

    @Test
    public void test1() {
        LOGGER.warn("TestClass2 - test1. Thread " + Thread.currentThread().getId());
    }
}

TestNG XML:

<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >

<suite name="Default Suite" parallel="classes" thread-count="3">
    <test name="example">
        <classes>
            <class name="com.stackover.project.TestClass1"/>
            <class name="com.stackover.project.TestClass2"/>
        </classes>
    </test>
</suite>

Output:

[TestClass1] [WARN] TestClass1 - test1. Thread 11
[TestClass1] [WARN] TestClass2 - test1. Thread 12
[TestClass1] [WARN] TestClass1 - test2. Thread 11

===============================================
Default Suite
Total tests run: 3, Passes: 3, Failures: 0, Skips: 0
===============================================

P.S: If TestClass1.test1() fails then TestClass1.test2() will be ignored.

Upvotes: 1

Related Questions