Can anyone explain me about Annotation @FindBy
in WebDriver
?
Where and why it is used?
Can anyone explain me about Annotation @FindBy
in WebDriver
?
Where and why it is used?
It's to assist with the construction of locators when using the Page Factory to support your Page Objects
However I'm discovering that I find it more useful to store your locators as By objects rather than WebElements as they are more flexible and you tend to avoid running into the StaleElementException.
By myLocator = By.id("idOfYourElement")
instead of
@FindBy(id = "idOfYourElement")
WebElement myLocator;
This way you can also use your locators when asserting the absence of an element or use it in the ExpectedConditions helpers.
You can also use Pagefactory, and have something like:
@FindBy(how = How.NAME, using = "logonName")
private WebElement logonNameField;
@FindBy(how = How.NAME, using = "password")
private WebElement passwordField;
Now, as for How., you can have:
Or you can use your own DOM Search plus Xpath, that would be outside of WebDriver API , but it should work.
With the help of PageFactory class, we use annotations @FindBy
to find WebElements. We use initElements method to initialize web elements. @FindBy
can accept tagName, partialLinkText, name, linkText, id, css, className, xpath as attributes.
The @FindBy
annotation locates one or more WebElements using a single criterion. For example, to identify all elements that have the same class attribute, we could use the following identification:
@FindBy(how = How.CLASS_NAME, using = "classname")
private List<WebElement> singlecriterion;`enter code here`
Can I cite API-documentation?
So, if you use
PageObject
pattern then you adds this annotation to class members andWebDriver
automatically inject appropriateWebElement
s to it during object initialization (whenPageFactory.initElements()
called).I strongly recommend to follow this link and read about
PageObject
pattern and@FindBy
annotations usage with more examples.