如何在不使用 PO 关闭 webdriver 的情况下 运行 进行测试?

How to run tests without closing webdriver using PO?

请帮助我完成我的 Selenium 项目。 Link 用于 GIT 存储库:https://kodov@bitbucket.org/kodov/addressbook5.git

我有一个要测试的应用程序地址簿 (https://sourceforge.net/projects/php-addressbook/)。 我对登录页面和创建新联系人的页面进行了多次测试。 案例是:

  1. 登录的负面测试
  2. 登录测试呈阳性
  3. 然后我不需要关闭浏览器,而是 运行 测试创建联系人。 问题是我做的POM和我的测试和页面不一样类,所以我不知道怎么退出 Webdriver 只是在所有测试之后,而不是在第一个测试之后。 也许我需要更改注释。

无论如何你都需要登录,所以你必须在两个测试中都包含登录部分。

您也可以尝试 @Test(dependsOnMethods = { "testName" }),但我不确定当您的测试在另一个文件中时这是否有效。

您可以创建一个基础测试 class 并使其他测试 class 扩展该 class。

例如:

public class BaseTest {

public static WebDriver driver;
private static boolean isTestsStarted;
public static WebDriverWait wait;

    @BeforeClass
    public static void setup() {
        // To run setup method before all tests that extends this base class
        if(!isTestsStarted) {
        System.setProperty("webdriver.chrome.driver", ConfProperties.getProperty("chromedriver_path"));
        driver = new ChromeDriver();
        wait = new WebDriverWait(driver, Duration.ofSeconds(10));
        driver.get(ConfProperties.getProperty("base_url"));
        isTestsStarted = true;
}
    }

    // To quit driver after all tests run
    // This will run only once, after all tests ran
    // Another advantage of this is, it will quit driver even though you stop the program manually
    static {
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            driver.quit();
        }));
    }

}

然后在你的测试 classes 中扩展这个基础 class 为您的登录测试 class

public class LoginTest extends BaseTest {

    public static LoginPage loginPage;
    public static MainPage mainPage;

    @BeforeClass
    public static void setup() {
        // You can call driver object since you initialized it in your parent class
        loginPage = new LoginPage(driver);
        mainPage = new MainPage(driver);
        driver.get(ConfProperties.getProperty("base_url"));
    }

    @Test
    public void testUserCanNotLoginWithInvalidCredentials() {
        loginPage.clearUsernameField().clearPasswordField()
                 .enterUsername(ConfProperties.getProperty("invalid_username"))
                 .enterPassword(ConfProperties.getProperty("invalid_password"))
                 .clickLoginButton();
        assertThat(loginPage.getLoginButton().isDisplayed()).isTrue();
    }

    @Test
    public void testUserCanLoginWithValidCredentials() {
        loginPage.clearUsernameField().clearPasswordField()
                 .enterUsername(ConfProperties.getProperty("valid_username"))
                 .enterPassword(ConfProperties.getProperty("valid_password"))
                 .clickLoginButton();
        assertThat(mainPage.getUserName())
                 .isEqualTo(ConfProperties.getProperty("valid_username"));
    }
}

用同样的方法,你可以在其他 classes 中使用你的驱动程序对象,如果你让那些 classes 扩展 BaseTest class