Access the By class created using @FindBy annotation in Selenium

17 July, 2014
We can access the By class created from the @FindBy. This is particularly useful to get detailed information when there is a NoSuchElementException.

Sample code for demonstration:

public class testPageObject {
   @FindBy(xpath = "//*[class='header']")
   WebElement element1;
 
   @FindBy(id = "search")
   WebElement element2;
 
    public testPageObject() {
       //Cache the WebElements using a 5 second wait
       PageFactory.initElements(new AjaxElementLocatorFactory(driver, 5), this);
   }
 
   public void printBy() {
        By element1 = getBy("element1");
        By element2 = getBy("element2");
 
        System.out.println(element1);
        System.out.println(element2);
   }
 
   private By getBy(String fieldName) {
       try {
            return new Annotations(this.getClass().getDeclaredField(fieldName)).buildBy();
       } catch (NoSuchFieldException e) { return null; }
 
The solution is to use Selenium’s built in Annotations class which takes a field and call buildBy() to return the By class for that field.

The output of the printBy() function:

By.xpath: //*[class=’header’]
By.id: search

No comments:

Post a Comment