复制/传递WebDriver实例如何工作,这很危险吗?

詹姆斯·马丁诺(James Martineau):

我已经在一个团队中工作了几个月,该团队正在开发Selenium WebDriver基础结构,关于我们从测试用例和页面对象访问驱动程序对象的方式有些困扰我。

我们的测试用例创建一个新的WebDriver实例并打开浏览器。这个新实例存储在测试用例类中。

然后,测试用例实例化页面对象。跟随Selenium的Page Object Pattern,这些页面对象将WebDriver作为其构造函数中的参数(尽管我注意到在我们的版本中它不是最终的)。各种页面对象方法都使用在页面对象的构造函数中设置的驱动程序来完成其工作。如果页面对象方法导航到新的页面对象,则将WebDriver传递给它。就像在Selenium的示例中一样:

public class LoginPage {
    private final WebDriver driver;

    public LoginPage(WebDriver driver) {
        this.driver = driver;

        // Check that we're on the right page.
        if (!"Login".equals(driver.getTitle())) {
            // Alternatively, we could navigate to the login page, perhaps logging out first
            throw new IllegalStateException("This is not the login page");
        }
    }

    // Conceptually, the login page offers the user the service of being able to "log into"
    // the application using a user name and password. 
    public HomePage loginAs(String username, String password) {
        // This is the only place in the test code that "knows" how to enter these details
        driver.findElement(By.id("username")).sendKeys(username);
        driver.findElement(By.id("passwd")).sendKeys(password);
        driver.findElement(By.id("login")).submit();

        // Return a new page object representing the destination. Should the login page ever
        // go somewhere else (for example, a legal disclaimer) then changing the method signature
        // for this method will mean that all tests that rely on this behaviour won't compile.
        return new HomePage(driver);
    }
}

这使得WebDriver实例似乎是唯一且重要的,就像必须将火炬从页面对象传递到页面对象一样。代码的风格使我认为我总是必须确保使用的驱动程序实例与上次操作中使用的实例相同。

但是,如果页面上有多个页面对象,并且页面对象方法不会返回您打算下一步使用的页面对象,这种“传递”就会变得复杂或不可能。当屏幕上有两个页面对象,并且需要在它们之间交替而不切换到新页面或创建新页面对象时,如何在同一个WebDriver实例上进行操作?

所有这些混乱使我相信实际上并不需要传递火炬,甚至可能没有发生(所有这些页面对象都存储了对同一WebDriver实例的引用吗?),但是我不知道为什么在这种情况下建议使用这种模式Selenium给出的描述。

因此,我是否需要担心“传递火炬”?或者,即使其他页面对象在此期间使用其自己版本的同一WebDriver进行操作,也可以用其WebDriver实例化任何页面对象后,它们能否正常运行?

将WebDriver设置为所有人都可以访问的单例会更容易/更好,因为在任何给定时间每个JVM我们不会使用多个WebDriver?然后,我们根本不需要在构造函数中传递WebDriver。预先感谢您的任何投入。

Harshavardhan Konakanchi:

最好将webdriver标记为整个框架的单例。我目前一直在使用这种模式,并且效果很好。
注意:处理并行执行时应格外小心。

@CodeEnthusiastic例如,以一个类为例GeneralLibrary,在其中创建一个WebDriver

将页面对象模型中的类扩展为父GeneralLibrary

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章