Java 将Selenium页面对象模式与WebDriverWait混合使用时出现问题

Java 将Selenium页面对象模式与WebDriverWait混合使用时出现问题,java,selenium,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) { WebD

我在项目中使用了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)
}
两个问题:

  • 因为我们只需要:

    waterer.until(ExpectedConditions.presenceOfElementLocated(
    By.id(“用户名”)).sendkey(用户名)

  • 而不是返回所需元素的页面对象用户名,页面对象模式是否无用

  • 如果页面对象模式是必需的,那么如何处理字符串“username”?我是否需要一个新类来维护常量,例如:

    public最终静态字符串USERNAME=“USERNAME”

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

    使用以下方法

    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)
    
    “…页面对象模式是否无用?”

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

    如果LoginPage.login()方法识别出登录页面上的预期错误,并且可以抛出测试可以响应的自定义异常,则可以将附加值添加到LoginPage.login()方法。我敢打赌,在登录页面上,您可能需要与其他内容进行交互,因此需要向LoginPage类添加其他方法

    我需要一个新类来维护常量吗


    我通常更喜欢将定位器的字符串保存在类中,它们将被使用。因此,我会在LoginPage中为USERNAME\u ID设置一个私有变量,然后您可以在其他地方使用它。

    希望下面的链接能够回答您的问题-