麻烦使用Selenium页面对象模式与WebDriverWait混合

时间:2016-10-14 03:27:56

标签: java selenium

我在项目中使用了selenium页面对象,并且还使用了WebDriverWait来等待元素添加。

@FindBy(how = How.ID, using = "username")
private WebElement username;

@FindBy(how = How.ID, using = "password")
private WebElement password;

public void login(String username, String password) {
    WebDriverWait waiter = new new WebDriverWait(driver, 5, 200);
    waiter.until(ExpectedConditions.presenceOfElementLocated(
       By.id("username")));
    this.username.sendKeys(username)
}

两个问题:

  1. 因为我们只需要:

    waiter.until(ExpectedConditions.presenceOfElementLocated( By.id("username"))).sendkey(username);

  2. 而不是页面对象用户名返回你想要的元素,页面对象模式是无用的吗?

    1. 如果页面对象模式是必要的,我该如何处理字符串" username"?我是否需要一个新类来维护常量,例如:

      public final static String USERNAME = "username";

    2. 所以我们可以在我的页面上调用它?

2 个答案:

答案 0 :(得分:1)

  

“......页面对象模式无用吗?”

几乎!例如,您的登录方法尚未在密码字段中输入值。因此,要在没有LoginPage.login()方法的情况下登录,您在miniumum需要在每个测试中使用两行长代码才能登录。

如果LoginPage.login()方法识别出登录页面上的预期错误,它可以抛出您的测试可以响应的自定义异常,则可以将其添加到您的LoginPage.login()方法中。我敢打赌,在登录页面上还有其他东西可能需要与之交互,因此需要添加到LoginPage类的其他方法。

  

我是否需要一个用于维护常量的新类

我通常更喜欢为将要使用它们的类中的定位器保留字符串。所以,我会在LoginPage中为USERNAME_ID设置一个私有变量,然后你可以在别处使用它。

答案 1 :(得分:0)

使用

等方法
waiter.until(ExpectedConditions.visibilityOf(username)); 
//org.openqa.selenium.support.ui.ExpectedConditions.visibilityOf(WebElement element)

而不是

waiter.until(ExpectedConditions.presenceOfElementLocated(By.id("username")));
//org.openqa.selenium.support.ui.ExpectedConditions.presenceOfAllElementsLocatedBy(By locator)