我需要所有测试都属于单个类,并并行运行这些测试。我在Testng.xml中使用parallel =“ methods”。我上课像
Public class DemoParallel{
@Test
/* some code to launch Google.*/
@Test
/* some code to launch Facebook*/
}
Actual:2次启动chrome。 Google测试已完全运行,Facebook测试仅启动但未运行。被绞死。只有一个测试通过,也曾尝试实现侦听器,但没有运气。 任何建议都会有所帮助。
答案 0 :(得分:0)
本地驱动程序工厂:
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
class LocalDriverFactory {
static WebDriver createInstance(String browserName) {
WebDriver driver = null;
if (browserName.toLowerCase().contains("firefox")) {
System.setProperty("webdriver.firefox.marionette","path to driver exe");
driver = new FirefoxDriver();
return driver;
}
if (browserName.toLowerCase().contains("internet")) {
driver = new InternetExplorerDriver();
return driver;
}
if (browserName.toLowerCase().contains("chrome")) {
System.setProperty("webdriver.chrome.driver","path to driver exe");
driver = new ChromeDriver();
return driver;
}
return driver;
}
}
按如下所示使用ThreadLocal类:
public class LocalDriverManager {
private static ThreadLocal<WebDriver> webDriver = new ThreadLocal<WebDriver>();
public static WebDriver getDriver() {
return webDriver.get();
}
static void setWebDriver(WebDriver driver) {
webDriver.set(driver);
}
}
创建Webdriver侦听器类:
import org.openqa.selenium.WebDriver;
import org.testng.IInvokedMethod;
import org.testng.IInvokedMethodListener;
import org.testng.ITestResult;
public class WebDriverListener implements IInvokedMethodListener {
@Override
public void beforeInvocation(IInvokedMethod method, ITestResult testResult) {
if (method.isTestMethod()) {
String browserName = method.getTestMethod().getXmlTest().getLocalParameters().get("browserName");
WebDriver driver = LocalDriverFactory.createInstance(browserName);
LocalDriverManager.setWebDriver(driver);
}
}
@Override
public void afterInvocation(IInvokedMethod method, ITestResult testResult) {
if (method.isTestMethod()) {
WebDriver driver = LocalDriverManager.getDriver();
if (driver != null) {
driver.quit();
}
}
}
}
测试类
public class ThreadLocalDemo {
@Test
public void testMethod1() {
invokeBrowser("https://www.google.com/");
}
@Test
public void testMethod2() {
invokeBrowser("http://www.facebook.com");
}
private void invokeBrowser(String url) {
System.out.println("Thread id = " + Thread.currentThread().getId());
System.out.println("Hashcode of webDriver instance = " + LocalDriverManager.getDriver().hashCode());
LocalDriverManager.getDriver().get(url);
}
}
Suite Xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite" parallel="methods">
<listeners>
<listener class-name="path-to-class-WebDriverListener"></listener>
</listeners>
<test name="Test">
<parameter name="browserName" value="firefox"></parameter>
<classes>
<class name="path-to-class-ThreadLocalDemo" />
</classes>
</test> <!-- Test -->
</suite> <!-- Suite -->