7

我重构了我的 java 项目,将 WebElement 选择器定义为 By 常量。这允许我将 By 常量传递给我的 findElement 方法,而无需在方法中评估 By 选择器类型。这是一个好主意吗?如果我将 By 变量定义为 public static final 常量,我可能会遇到什么问题?

下面是一个例子:

public static final By LOGIN_BUTTON_SELECTOR = By
        .cssSelector("input[name='logIn']");

/**
 * click the Login button
 */
public void clickLoginButton() throws TimeoutException,
        StaleElementReferenceException {
    // click the Login button
    clickElement(LoginPage.LOGIN_BUTTON_SELECTOR);
}

/**
 * 
 * find an element
 * 
 * click the element
 * 
 */
public void clickElement(By elementSelector) throws TimeoutException,
        StaleElementReferenceException {

    WebElement webElement = null;

    // find the element by By selector type
    webElement = getElement(elementSelector);

    // click the element
    webElement.click();

}

/**
 * 
 * generic method to get a WebElement using a By selector
 * 
 */
public WebElement getElement(By elementSelector) throws TimeoutException {

    WebElement webElement = null;

    // find an element using a By selector
    getDriverWait().until(
    ExpectedConditions.presenceOfElementLocated(elementSelector));
    webElement = getDriver().findElement(elementSelector);

    return webElement;
}
4

1 回答 1

4

这是一个很好的做法。

您可以将它与 PageObject 一起使用,请参见示例:

https://code.google.com/p/selenium/wiki/PageObjects

于 2013-06-06T09:26:27.023 回答