I decided to write this post because it has been several times already that my students encountered the same question over and over in job interviews. It’s a question that indicates an understanding of Page Objects Design Pattern and it goes like this: “What is the difference between the FindAll vs. FindBys annotation in Page Objects?” π€
Anyone who has ever used Page Objects, will surely be familiar with the popular FindBy annotation, with which we can identify elements on the DOM, as seen in the example below:
@FindBy(how = How.ID, using = "123") private WebElement testElement
Or in its shorter version:
@FindBy(id = "123") private WebElement testElement
This means: find me an element on the page with an id that has the value: 123
The FindAll and FindBys annotations, however, are much less popular than the previous FindBy. Let’s go ahead and learn about them and understand the FindAll vs. FindBys differences.
FindAll vs. FindBys Selenium Annotations
Let’s take a look at the official Selenium WebDriver documentation:
Starting with FindAll:
https://www.selenium.dev/selenium/docs/api/java/org/openqa/selenium/support/FindAll.html
And now moving on to the FindBys docs:
https://www.selenium.dev/selenium/docs/api/java/org/openqa/selenium/support/FindBys.html
We can see that these two annotations are implemented under the org.openqa.selenium.support library, but still – there are differences.
The FindBys annotation is actually a container of annotations, which means that within it we can write several FindBy annotations (one or more), and within each FindBy we can define some sort of search criteria, so that the FindBys will return a list of the elements that meet all the FindBy criteria. Let’s simplify this confusing sentence with an example π‘ This is the HTML from which we want to find elements:
Now, let’s use the FindBys annotation:
@FindBys({ @FindBy(css = "li[key='android']"), @FindBy(css = "li[key='ios']") }) private List exampleFindBys;
We can see here the identification of elements with key=android and with key=ios, and in this scenario our list will be empty. Why? Because in the HTML DOM we don’t have elements that meet the search criteria: “Find elements that have both key=android and key=ios”
Now, let’s use the FindAll annotation:
@FindAll({ @FindBy(css = "li[key='android']"), @FindBy(css = "li[key='ios']") }) private List exampleFindAll;
In this case, our list will contain 3 components, since the search criteria is: “Find elements that have an element with key=android or have an element with key=ios”.
In other words, it can be said that FindBys works with the AND operator, while FindAll works with the OR operator.
Hope this will help you once you go to your next interview!
Good Luck and Happy Testing π
β
Reference:Β https://atidcollege.co.il
Really helpful! Thanks for sharing π