我将 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>
最佳答案
之所以在运行其他方法的地方分离出不同的线程,是因为您通过选择parallel="tests"
启用了并行策略。 .
如果您希望所有配置方法在同一线程上运行,则应通过设置 parallel="false"
来禁用并行性。在你的<suite>
标签。
关于java - 为什么@BeforeSuite和@AfterSuite在单独的线程中运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62171172/