我正在尝试在我的TestNG项目中运行多个类,但其中一个类总是失败。
AbstractTest.java (sampleTest1和sampleTest2类只包含一个带有get()方法的@Test)
public class AbstractTest {
private List<WebDriver> webDriverPool = Collections.synchronizedList(new ArrayList<WebDriver>());
private ThreadLocal<WebDriver> driverThread;
@BeforeTest
public void beforeTest()
{
this.driverThread = new ThreadLocal<WebDriver>() {
@Override
protected WebDriver initialValue() {
final WebDriver webDriver = new FirefoxDriver();
webDriverPool.add(webDriver);
return webDriver;
}
};
}
@AfterTest
public void afterTest() {
for (WebDriver driver : this.webDriverPool) {
driver.quit();
}
}
public WebDriver getDriver() {
return this.driverThread.get();
}
}
的testng.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite thread-count="11" name="testSuite" parallel="tests">
<test name="Test1" group-by-instances="true">
<classes>
<class name="test.sample.sampleTest1" />
<class name="test.sample.sampleTest2" />
</classes>
</test> <!-- Test1 -->
</suite> <!-- testSuite -->
问题是其中一个线程没有看到WebDriver,它返回null并且将失败。我知道如果我将ThreadLocal更改为静态它将起作用但如果我并行运行我的测试会导致更多问题,我的目标是什么:)
提前致谢!
答案 0 :(得分:0)
使用其他方法使用ThreadLocal。例如一种线程安全的单例实现可以提供帮助:
public class DriverSession
{
private static ThreadLocal<DriverSession> instance = new ThreadLocal<DriverSession>();
private WebDriver driver;
public static DriverSession getInstance()
{
if (null == instance.get())
{
instance.set(new Proxy1());
}
return instance.get();
}
protected DriverSession()
{
driver = new FirefoxDriver();
}
public WebDriver getDriver()
{
return this.driver;
}
}
我就是这样做的。所以为了访问当前的驱动程序实例使用:
DriverSession.getInstance().getDriver().get("http://google.com");