Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selenium WebDriver - Is defining WebElement selectors as a By constant a good idea?

I have refactored my java project to define the WebElement selectors as By constants. This allows me to pass a By constant into my findElement method, without requiring an evaluation of the By selector type in the method. Is this a good idea? What issues am I likely to encounter if I define the By variables as public static final constants?

Following is an example:

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;
}
like image 629
Lori Johnson Avatar asked Jun 05 '13 17:06

Lori Johnson


1 Answers

It is a good practice.

You can use it with PageObject, see example:

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

like image 70
Ittiel Avatar answered Sep 29 '22 21:09

Ittiel