为什么@BeforeSuite和@AfterSuite会在一个单独的线程中运行?

问题描述 投票:0回答:1

我将ThreadLocal变量初始化为@BeforeSuite的一部分。但由于它是在一个单独的线程中运行,初始化的变量没有传递给@Test。谁能向我解释一下这种行为背后的原因?我们能否让 @BeforeSuite 与其他注解方法一样,作为同一线程的一部分运行?

程式碼

import org.testng.annotations.*;

public class SampleTest {

ThreadLocal<String> s = new ThreadLocal<>();

@BeforeSuite
public void beforeSuite(){
    System.out.println("beforeSuite");
    s.set("Initialisation value");
    System.out.println(Thread.currentThread().getId());
}

@BeforeClass
public void beforeclass(){
    System.out.println("beforeclass");
    System.out.println(Thread.currentThread().getId());
}

@BeforeTest
public void beforetest(){
    System.out.println("beforetest");
    System.out.println(Thread.currentThread().getId());
}

@BeforeMethod
public void beforemethod(){
    System.out.println("beforemethod");
    System.out.println(Thread.currentThread().getId());
}

@AfterMethod
public void aftermethod(){
    System.out.println("aftermethod");
    System.out.println(Thread.currentThread().getId());
}

@AfterTest
public void afterTest(){
    System.out.println("afterTest");
    System.out.println(Thread.currentThread().getId());
}

@AfterClass
public void afterclass(){
    System.out.println("afterclass");
    System.out.println(Thread.currentThread().getId());
}

@AfterSuite
public void afterSuite(){
    System.out.println("afterSuite");
    System.out.println(Thread.currentThread().getId());
}

@Test
public void testMethod(){
    System.out.println(Thread.currentThread().getId());
    System.out.println("My actual Test");
    System.out.println("Value of threadlocal variable s : "+s.get());
}

}

代码输出

beforeSuite
1

beforetest
11

beforeclass
11

beforemethod
11

11
My actual Test
Value of threadlocal variable s : null

aftermethod
11

afterclass
11

afterTest
11

afterSuite
1  

===============================================
Titan Automation
Total tests run: 1, Passes: 1, Failures: 0, Skips: 0
===============================================

Testng.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="Automation" parallel="tests">
    <test name="Test Cases" thread-count="4">
        <classes>
            <class name="org.example.SampleTest"></class>
        </classes>
    </test>
</suite>
java multithreading automation testng
1个回答
0
投票

之所以在运行其他方法的地方有不同的线程被分离出来,是因为您通过选择了 parallel="tests".

如果你想让所有的配置方法在同一个线程上运行,你应该通过设定 parallel="false" 在你 <suite> 标签。

© www.soinside.com 2019 - 2024. All rights reserved.