前言
在运行测试用例的时候,经常会考虑到并发执行测试用例的情况。通常会使用testng的套件来解决多个用例的执行,但在testng的套件执行中,会有这样一个问题,
我在一个testNG的case里新建两个webdriver,再做操作,他们就会冲突。然后其中一个会死掉。
如果我们直接用testNG的多线程,也会遇到类似的问题。
因为selenium webdriver本身不是线程安全的,这里,我用thread local来解决线程安全问题:
public static ThreadLocal<WebDriver> threadDriver = new ThreadLocal<WebDriver>() ;
当前进程未绑定driver时,创建一个driver,如果已绑定driver,则直接返回。使用的是ThreadDriver.set(driver):
if (null != threadDriver.get()) {
try {
threadDriver.set(new FireFoxDriver());
return;
} catch (Exception e) {
logger.error(e);
stop();// 处理浏览器异常情况,关闭异常driver
}
}
return DriverManager.ThreadDriver.get();
如此以为,线程就安全了,
当dataprovider设置了parallel参数为true时,测试即会并发执行。这里的真实并发数受到CPU内核数限制(Testng的东西自己研究去~)