我有一个测试用例包含两种方法。在两个浏览器实例中尝试这两种测试方法时,只有一个浏览器实例可以打开网站,但其余步骤无法执行。另一个浏览器实例甚至无法打开网站(空白页面)。
我已经尝试过 Stackoverflow 上建议的解决方案。这些解决方案不适用于我的情况。
public class RunSimpleTest{
private String baseUrl = "https://mywebsite";
public WebDriver driver;
GlobalFunctions objGlobalFunc;
@BeforeMethod(alwaysRun = true)
public void setup() {
try{
// declaration and instantiation of objects/variables
System.setProperty("webdriver.chrome.driver", "C:/ChromeDriver/chromedriver.exe");
// Disable Chrome Developer Mode Extension
ChromeOptions options = new ChromeOptions();
options.addArguments("--disable-extensions");
options.addArguments("--start-maximized");
driver = new ChromeDriver(options);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
objGlobalFunc = new GlobalFunctions(driver);
driver.get(baseUrl);
objGlobalFunc = new GlobalFunctions(driver);
objGlobalFunc.selectEnglishLanguage();
}
catch (Exception e){
e.printStackTrace();
}
}
@Test
public void BTRun1() {
objGlobalFunc.setUserNameValue("ABC");
objGlobalFunc.clickOKBtnOnMEXLoginForm();
}
@Test
public void BTRun2() {
objGlobalFunc.setUserNameValue("ABC");
objGlobalFunc.clickOKBtnOnMEXLoginForm();
}
}
BTRun1 在 Chrome 浏览器中打开。并且,用户可以登录。
BTRun2 在另一个 Chrome 浏览器中打开。并且,用户可以登录。
最佳答案
代码的核心问题是全局 WebDriver 对象的使用。
并行运行时,TestNG 仅创建一个 RunSimpleTest 实例,即 WebDriver 对象的一个实例。这导致两个测试在与 WebDriver 对象通信时相互覆盖。
一种解决方案是使用 ThreadLocalDriver 和 ThreadLocalGlobalFunctions:
protected ThreadLocalDriver threadLocalDriver;
protected ThreadLocalGlobalFunctions threadLocalGlobalFunctions;
public void setup() {
try{
// declaration and instantiation of objects/variables
System.setProperty("webdriver.chrome.driver", "C:/ChromeDriver/chromedriver.exe");
// Disable Chrome Developer Mode Extension
ChromeOptions options = new ChromeOptions();
options.addArguments("--disable-extensions");
options.addArguments("--start-maximized");
threadLocalDriver = new ThreadLocalDriver(options);
threadLocalDriver.getDriver().manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
objGlobalFunc = new ThreadLocalGlobalFunctions(threadLocalDriver.getDriver());
threadLocalDriver.getDriver().get(baseUrl);
objGlobalFunc.getGlobalFunc().selectEnglishLanguage();
}
catch (Exception e){
e.printStackTrace();
}
}
@Test
public void BTRun1() {
objGlobalFunc.getGlobalFunc().setUserNameValue("ABC");
objGlobalFunc.getGlobalFunc().clickOKBtnOnMEXLoginForm();
}
@Test
public void BTRun2() {
objGlobalFunc.getGlobalFunc().setUserNameValue("ABC");
objGlobalFunc.getGlobalFunc().clickOKBtnOnMEXLoginForm();
}
要了解有关将 ThreadLocal 与 WebDriver 结合使用的更多信息,请查看:http://seleniumautomationhelper.blogspot.com/2014/02/initializing-webdriver-object-as-thread.html
关于java - 如何使用 TestNG 在两个不同的浏览器中并行运行两个测试方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56231955/