Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in DevOps and Agile by (19.7k points)

Why should I use @FindBy vs driver.findElement()?

@FindBy forces me to move all my variables to a class level (when most of them only need to be at the method level). The only thing it seems to buy me is I can call PageFactory.initElements(), which handles lazy initialization for me.

What am I missing?

1 Answer

0 votes
by (62.9k points)

Roughly speaking, this(@FindBy) annotation is simply an alternative way of finding web-elements in a web application (the “usual way” is driver.findElement(), as you said).

The main advantage of this annotation(@FindBY) is that it supports the PageObject template, which allows you to create a class for each page of the system that you are trying to test.

So instead of having (plain driver.findElement()code):

public class TestClass {

    public void testSearch() {

        WebDriver driver = new HtmlUnitDriver();

        driver.get("http://www.google.com/");

        Element searchBox = driver.findElement(By.name("q"));

        searchBox.sendKeys("stringToSearch");

        searchBox.submit();

        // some assertions here

    }

You define a class for the page (with annotation @FindBy for the elements being used):

public class GooglePage {

    @FindBy(how = How.NAME, using = "q")

    private WebElement searchBox;

    public void searchFor(String text) {

        searchBox.sendKeys(text);

        searchBox.submit();

    }

}

And use it like:

 public class TestClass {

    public void testSearch() {

        WebDriver driver = new HtmlUnitDriver();

        driver.get("http://www.google.com/");

        GooglePage page = PageFactory.initElements(driver, GooglePage.class);

        page.searchFor("stringToSearch");

        // some assertions here

    }

}

Now I know that at first, it may seem verbose, but just give it a moment and think that there are several tests for this page. What if the name changes searchBox? (From name "q" to id, say query?)

In which code would there be more changes to make it work again? Unit with or without page objects ( @FindBy)? If the page greatly changes its structure, in which code will the maintenance be easier?

There are other benefits, such as additional annotations, for example:

@FindBy(name = "q")

@CacheLookup

private WebElement searchBox;

After @CacheLookup triggers an item, the search would only happen once. After that, it will be cached in a variable.

Hope this helps. 

If you are interested to learn Selenium on a much deeper level and want to become a professional in the testing domain, check out Intellipaat’s Selenium 3.0 certification!

Browse Categories

...