How does Selenium Annotation "@FindBy" work when it returns no element?

749 Views Asked by At

If @FindBy returns no element, do we get error as I saw @FindBy could be used to get 0 to multiple elements.

Scenario: @FindBy(id = "btn") private WebElement searchButton; //allows single element to be referenced

Case 1: If we have no elements having id as "btn", then what would be the result? Case 2: If we have multiple elements having id as "btn",then what would be the result?

Please clarify.

2

There are 2 best solutions below

0
Guy On

You won't receive an error when calling PageFactory.initElements, element that wasn't found will be set to null. However you will get NullPointerException when you try to use the element.

2
Mukunthan Ragavan On

Case 1: If we have no elements having id as "btn", then what would be the result?

org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"name","selector":"<invalid name>"}

Case 2: If we have multiple elements having id as "btn",then what would be the result?

Since we have multiple elements, we could not do any actions due to ambiguity.

org.openqa.selenium.WebDriverException: unknown error: cannot focus element