gpt4 book ai didi

java - 当 DataProvider 上的并行设置为 true 时,并行执行测试会引发异常 - TestNG

转载 作者:行者123 更新时间:2023-12-02 09:05:45 25 4
gpt4 key购买 nike

当 DataProvider 上的 parallel=true 时,并行执行测试会引发以下异常。两个浏览器实例将打开并在单独的线程上运行,但只有一个浏览器实例会成功执行,而另一个浏览器实例会陷入尝试查找元素并引发异常的情况。请问,当 dataprovider 中的parallel=true 时,如何使测试成功执行。我缺少一些东西,可能是 BasePage 中的 WebDriver 实例。请帮忙。谢谢。

[PoolService-1] 15:44:06,447 INFO  [Default test] Close driver
PASSED: loginTest("unresticteduser@gmail.com", "123456")
FAILED: loginTest("resticteduser@gmail.com", "123456")

WARNING: WebDriverException thrown by findElement(By.xpath: //button[contains(text(), 'NO THANKS')])
org.openqa.selenium.WebDriverException: org.apache.http.conn.HttpHostConnectException: Connect to
localhost:8478 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect

当 dataprovider 上的parallel=false 时,测试将在数据输入到测试并成功执行时一次打开一个浏览器实例。

PASSED: loginTest("unresticteduser@gmail.com", "123456")
PASSED: loginTest("resticteduser@gmail.com", "123456")

这是我编写的代码:

1) 浏览器工厂

public class BrowserDriverFactory {

private ThreadLocal<WebDriver> driver = new ThreadLocal<WebDriver>();
private String browser;
private Logger log;

public BrowserDriverFactory(String browser, Logger log) {
this.browser = browser.toLowerCase();
this.log = log;
}

public WebDriver createDriver() {
// Create driver
log.info("Create driver: " + browser);

if(browser.equals("chrome")) {
System.setProperty("webdriver.chrome.driver", "src/main/resources/chromedriver.exe");
driver.set(new ChromeDriver());
}
else if(browser.equals("firefox")) {
System.setProperty("webdriver.gecko.driver", "src/main/resources/geckodriver.exe");
driver.set(new FirefoxDriver());
}
else {
System.out.println("Do not know how to start: " + browser + ", starting chrome.");
System.setProperty("webdriver.chrome.driver", "src/main/resources/chromedriver.exe");
driver.set(new ChromeDriver());
}

return driver.get();
}

}

2)基础测试

public class BaseTest {

protected WebDriver driver;
public WebDriverWait wait;
protected Logger log;
protected FirefoxProfile profile;
protected String url = "http://www.qaclickacademy.com/";

protected String testSuiteName;
protected String testName;
protected String testMethodName;

@BeforeMethod(alwaysRun = false)
public void setUp(Method method, ITestContext ctx) {
String testName = ctx.getCurrentXmlTest().getName();
log = LogManager.getLogger(testName);

BrowserDriverFactory factory = new BrowserDriverFactory(config.getBrowser(), log);
driver = factory.createDriver();
driver.get(url);

profile=new FirefoxProfile();
// Set preferences for file type
profile.setPreference("browser.helperApps.neverAsk.openFile", "application/octet-stream");

driver.manage().window().maximize();
wait = new WebDriverWait(driver, 5);

this.testSuiteName = ctx.getSuite().getName();
this.testName = testName;
this.testMethodName = method.getName();
}

@AfterMethod(alwaysRun = true)
public void tearDown(ITestResult result) {

if(result.getStatus()==ITestResult.FAILURE) {
//capture screenshot
}

log.info("Close driver");
// Close browser
driver.quit();
}
}

3)数据提供者

 @DataProvider(name="SearchProvider", parallel=true)
public Object[][] getDataFromDataprovider(){
return new Object[][]
{
{ "unresticteduser@gmail.com", "123456" },
{ "resticteduser@gmail.com", "123456" }
};

}

4)基本页面

 public class BasePage { 
protected WebDriver driver;
public WebDriverWait wait;
protected Logger log;

public BasePage(WebDriver driver, Logger log) {
this.driver = driver;
this.log = log;
wait = new WebDriverWait(driver, 5);
}

protected void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

protected void clickStallElement(By locator) {

try {
waitForVisibilityOf(locator, 30);
findElement(locator).click();
}
catch(org.openqa.selenium.StaleElementReferenceException ex)
{
waitForVisibilityOf(locator, 30);
findElement(locator).click();
}
}


/** Open page with given URL */
protected void openUrl(String url) {
driver.get(url);
}

/** Find element using given locator */
protected WebElement findElement(By locator) {
return driver.findElement(locator);
}

/** Find all elements using given locator */
protected List<WebElement> findAllElements(By locator) {
return driver.findElements(locator);
}

/** Click on element with given locator when its visible */
protected void click(By locator) {
waitForVisibilityOf(locator, 30);
findElement(locator).click();
log.info("Clicked WebElement");
}

...

}

5) 基础测试

public class SignInPageTest extends BaseTest {


@Test(dataProvider = "SearchProvider", dataProviderClass = DBDataProvider.class)
public void loginTest(String username, String password) {

System.err.println("Running Test=> " + this + " -> on thread [" + Thread.currentThread().getId() + "]");

log.info("Starting LogInTest # for " + username);

ClickAcadamyLandingPage home = new ClickAcadamyLandingPage(driver, log);
home.openPage();

home.closeNewsLetterPopup();

// click login
ClickAcadamyLoginPage loginPage = new ClickAcadamyLoginPage(driver, log);
loginPage = home.clickLoginBtn();

loginPage.enterEmailAddress(username);

loginPage.enterPassword(password);

ClickAcadamyDashboard dashboard = loginPage.clickLogin();
dashboard.clickLogout();

}


}

6)testng.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite" data-provider-thread-count = "2" thread-count="2" verbose="1" parallel="tests">

<listeners>
<listener class-name="com.paralleltest.basetest.TestListener"/>
</listeners>

<test name="loginTest">
<classes>
<class name="com.paralleltest.SignInPageTest"/>
</classes>
</test>

</suite>

最佳答案

问题出在你的测试代码上。当您并行运行测试并由数据提供程序提供支持时,您的 Webdriver 实例将在测试方法之间共享。

这是 BaseTestBrowserDriverFactory 的修复版本,包含线程安全性。

import java.lang.reflect.Method;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.ITestContext;
import org.testng.ITestResult;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;

public class BaseTest {
private static final ThreadLocal<WebDriver> drivers = new ThreadLocal<>();
public WebDriverWait wait;
protected FirefoxProfile profile;
protected String url = "http://www.qaclickacademy.com/";

protected String testSuiteName;
protected String testName;
protected String testMethodName;

public WebDriver getDriver() {
return drivers.get();
}

@BeforeMethod()
public void setUp(Method method, ITestContext ctx) {
String testName = ctx.getCurrentXmlTest().getName();

WebDriver driver = BrowserDriverFactory.createDriver("firefox");
drivers.set(driver);
driver.get(url);

driver.manage().window().maximize();
wait = new WebDriverWait(driver, 5);

this.testSuiteName = ctx.getSuite().getName();
this.testName = testName;
this.testMethodName = method.getName();
}

@AfterMethod(alwaysRun = true)
public void tearDown(ITestResult result) {
getDriver().quit();
drivers.remove();
}
}

BrowserDriverFactory.java

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.firefox.FirefoxProfile;

public class BrowserDriverFactory {

public static WebDriver createDriver(String browser) {
System.err.println("Create driver: " + browser);

if (browser.equals("chrome")) {
System.setProperty("webdriver.chrome.driver", "src/main/resources/chromedriver.exe");
return new ChromeDriver();
} else if (browser.equals("firefox")) {
System.setProperty("webdriver.gecko.driver", "src/main/resources/geckodriver.exe");
FirefoxOptions options = new FirefoxOptions();
FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("browser.helperApps.neverAsk.openFile", "application/octet-stream");
options.setProfile(profile);
return new FirefoxDriver(options);
}
System.out.println("Do not know how to start: " + browser + ", starting chrome.");
System.setProperty("webdriver.chrome.driver", "src/main/resources/chromedriver.exe");
return new ChromeDriver();
}
}

现在,在扩展 BaseTest 的测试类的所有测试方法中,每当您需要访问驱动程序对象时,您都可以通过调用 getDriver() 方法来获取它。

您可以在我的博客中找到完整的解释和更多相关解释:https://rationaleemotions.com/parallel_webdriver_executions_using_testng/

我还创建了一个库,它可以抽象出 webdriver 生命周期管理,并通过自定义注释使您的管理变得更加简单。

看看https://github.com/rationaleEmotions/autospawn

关于java - 当 DataProvider 上的并行设置为 true 时,并行执行测试会引发异常 - TestNG,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59827491/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com