使用testNG并行化测试时,类中的测试不会在同一线程中执行

时间:2018-11-07 08:03:07

标签: java class parallel-processing testng selenide

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(singleThreaded = true)
public class ExampleTest {

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

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

测试在三个线程中运行,但是第一个测试在一个线程中运行,第二个测试分别在第二个线程中运行,第二个测试下降,因为它取决于第一个线程。如何运行并行测试,以使一个类中的所有测试都在一个线程中执行?

谢谢。

1 个答案:

答案 0 :(得分:0)

TestNG中存在一个错误。这是link to GitHub issue

7.0.0-beta1开始是固定的。但是您应该将-Dtestng.thread.affinity=true设置为JVM参数。 IntelliJ IDEA步骤:转到运行->编辑配置:

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>

输出:

[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:如果TestClass1.test1()失败,那么TestClass1.test2()将被忽略。