Search code examples
javaselenium-webdriverfactory-pattern

@Findby vs. By cons and pros?


I started a PageFactory framework and started using @FindBy without really knowing much about it, besides reading that this was an advanced method.

What I realized is ExpectedConditions.presenceOfElementLocated does not work with WebElements. So i had to use .visibilityOf which is not the same, and sometimes it won't perform actions on my elements.

So I changed it to a By method and now the locators work perfectly fine again.

Is the By class is more robust for storing elements?

Which would be less problem prone? @Findby or By


Solution

  • @FindBy attribute is very helpful for static elements. The elements that are not loaded dynamically can easily be mapped in a cleaner way using @FindBy attribute. You are using Expected conditions because the elements are not loaded instantly and Selenium needs to wait for the element to load or do a regular check for it's existence. In that cases, @FindBy would not work and you have to use By selectors. In such case I create private fields in order to reduce code duplications. As per my knowledge, using @FindBy is a cleaner way for element mapping in page Object Pattern which is not possible to use in every scenario and that's the only benefit of using that.

    Example of how private field can be used for elements mapping

    private static readonly By TestSelector = By.XPath("Your xpath");
    
    public void ClickUpdate()
    {
        //Use same selector/field
        Driver.FindElement(TestSelector).Click();
    }
    
    public void ClickUpdate2()
    {
        //Use same selector/field
        Driver.FindElement(TestSelector).Click();    
    }
    

    Note: C# code