首页 > 解决方案 > 一个接一个地执行 Selenium 测试,而无需通过 testng 重新启动浏览器

问题描述

我有两个必须执行的测试用例
1.登录到应用程序
2.执行一些操作

下面是我的代码设计:
BaseTest.java

public abstract class BaseTest {

    public WebDriver driver;

    @BeforeSuite
    public void openApplication() {
        System.setProperty(chrome_key,chrome_value);
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--disable-notifications");
        driver = new ChromeDriver(options);
        driver.manage().window().maximize();
        driver.get(url);
    }
}

登录页面.java

public class LoginPage extends BasePage{
    @FindBy (xpath = "//input[@id='username']")
    WebElement userName;

    @FindBy (xpath = "//input[@id='password']")
    WebElement password;    
    public LoginPage(WebDriver driver) {
        super(driver);
        PageFactory.initElements(driver, this);
    }

    public void loginToApp(String username, String pwd) {

    }
}

帐户.java:

public class NewAccount extends BasePage{
    @FindBy(xpath = "//span[text()='Accounts']/../..")
    WebElement accountsTab;

    public NewAccount(WebDriver driver) {
        super(driver);
        PageFactory.initElements(driver, this);
    }

    public void createNewAccount() {    
    }
}

LoginToApp.java:

public class LoginToApp extends BaseTest {
    @Test
    public void a_verifyLogin() throws IOException {
        LoginPage hp = new LoginPage(driver);
        hp.loginToApp(username, password);
    }
}

创建帐户.java:

public class CreateAccount extends BaseTest {
    @Test
    public void b_createAccountRecord() {
        NewAccount na = new NewAccount(driver);
        na.createNewAccount();
    }
}

testng.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="Suite">
  <test name="Test">
    <classes>
      <class name="com.testcases.LoginToApp"/>
      <class name="com.testcases.CreateAccount"/>
    </classes>
  </test> <!-- Test -->
</suite> <!-- Suite -->

使用此框架结构,当我执行 testng.xml 文件时,LoginToApp 中的第一个测试按预期执行。当控件进入 CreateAccount 中的测试时,驱动程序变为 Null,因此无法执行第二次测试。

预期流程:
1.初始化浏览器
2.启动 url
3.执行
LoginToApp.java 的 @Test 方法 4.执行 CreateAccount.java 的 @Test 方法

是否可以在不将 WebDriver 设为静态的情况下实现上述流程?如果是,请解释。

标签: javaseleniumselenium-webdrivertestng

解决方案


1.Initialise Browser  (set this under before method)
2.Launch the url      (give priority =0)
3.Execute the @Test method of LoginToApp.java  (give priority =1)
4.Execute the @Test method of CreateAccount.java( give depends on method )

depends on method only execute if your loginapp test successfully run 

推荐阅读