虽然我正在使用TestNG和selenium-webdriver运行并行测试用例,但是有些浏览器实例打开时是空的,即使执行完成也不会关闭。我已经在不同的论坛上阅读了几个主题,询问类似问题,但似乎没有一个是同一问题。
当我向套件添加更多测试时,似乎还打开了更多空浏览器。以下是与Java类和testng xml相关的信息:
这是我的TestNg.xml:
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="Automation Suite" verbose="2" parallel="classes" thread-count="5">
<listeners>
<listener class-name="com.qa.extentreportlistener.ExtentReportListener"></listener>
</listeners>
<test name="Sanity Test0" parallel="methods" thread-count="3" >
<classes>
<class name="test.test0" />
</classes>
</test>
<test name="Sanity Test1" parallel="methods" thread-count="3">
<classes>
<class name="test.test1" />
</classes>
</test>
<test name="Sanity Test2" parallel="methods" thread-count="3">
<classes>
<class name="test.test2" />
</classes>
</test>
<test name="Sanity Test3" parallel="methods" thread-count="3">
<classes>
<class name="test.test3" />
</classes>
</test>
</suite>
下面是用于设置和获取Thread本地Webdriver的类:
public class WebdriverFactory {
private static ThreadLocal<WebDriver> tlDriver = new ThreadLocal<>();
public synchronized static void setTLDriver () {
String type = TestConfig.getInstance().getProperty(TestConfigKeys.BROWSER).toLowerCase().trim();
if (type.equals("firefox")) {
tlDriver = ThreadLocal.withInitial(() -> new FirefoxDriver(OptionsManager.getFirefoxOptions()));
} else if (type.equals("chrome")) {
tlDriver = ThreadLocal.withInitial(() -> new ChromeDriver(OptionsManager.getChromeOptions()));
}
Log.info("Running setTLDriver -- Browser is "+type +" and Thread Id is "+ Thread.currentThread().getId() );
}
public synchronized static WebDriver getTLDriver ()
{
Log.info("Running getTLDriver -- Thread Id is "+ Thread.currentThread().getId());
return tlDriver.get();
}
}
AbstractTestCase从WebDriverFactory调用Thread本地驱动程序,并由每个测试类扩展:
public abstract class AbstractTestCase {
protected static ReportDispatcher report = ReportManager.getInstance();
private static String url = TestSUT.getInstance().getStringProperty("url");
protected AssertUtils myAssert;
protected Verify verify;
public static Properties props =null;
//protected WebDriver driver = WebdriverFactory.getTLDriver();
@BeforeMethod(alwaysRun = true)
public void setup() throws Throwable, IOException
{
Log.startLog("AbstractTestCase: Test is starting");
WebdriverFactory.setTLDriver();
WebDriver driver = WebdriverFactory.getTLDriver();
driver = new EventFiringWebDriver(driver);
((EventFiringWebDriver) driver).register(new ScreenshotEventListener());
driver.manage().timeouts().implicitlyWait(Integer.valueOf(TestConfig.getInstance().getProperty(TestConfigKeys.DRIVER_IMPLICITY_WAIT)), TimeUnit.SECONDS);
verify = new Verify(driver);
myAssert = new AssertUtils(driver);
driver.get(url);
}
@AfterMethod(alwaysRun = true)
public void tearDown()
{
if (WebdriverFactory.getTLDriver() != null) {
Log.endLog("AbstractTestCase: Test is ending");
WebdriverFactory.getTLDriver().quit();
}
}
}
如果不并行运行,则测试将按预期运行。问题是孤立的浏览器在并行运行时会导致一些测试失败。
如果上述代码做错了,请告诉我。感谢您的帮助!