0

I am creating a Page Object framework while going through the concepts of it, I got to know that Page Factory(@FindBy) is used in conjunction with Page Objects. However, I am not able to understand why do I need to use @FindBy when I can use driver.findElement with my locators in Page Object class. For instance :

//Code with @FindBy

  public class LoginPage{

      public LoginPage(WebDriver driver)){
      PageFactory.initElements(driver,this);
     }

     public WebElement q;

    }

    public class TestCase{

WebDriver driver=new FirefoxDriver();
LoginPage logPage=new LoginPage(driver);

 public void enterUserName(){
   logPage.q.sendKeys("username");

}
}

//Code with driver.findElement

public class LoginPage{

 public WebElement q=driver.findElement(By.id('q'));

}

public class TestCase{
WebDriver driver=new FirefoxDriver();
 LoginPage logPage=new LoginPage();

 public void enterUsername(){
  logPage.q.sendKeys("username");
}

}

What is the difference between both the codes over here as both the codes are essentially doing the same thing ?

brij
  • 331
  • 1
  • 5
  • 17

1 Answers1

0

Fundamentally there probably isn't a massive difference in terms of how tests will run, and what the driver is doing, whether you're using Driver.FindElement() or the @FindBy annotation. The "benefits" of using @FindBy, in my opinion are that it guides you towards keeping all WebElements and Methods relevant to a specific page in one location, and it separates the finding of the elements of your page from the methods you're carrying out on the page, e.g. see below for a brief example Login page (in C#):

public class LoginPage
{
    public IWebDriver Driver;

    [FindsBy(How = How.Id, Using = "username")]
    public IWebElement UsernameField;

    [FindsBy(How = How.Id, Using = "password")]
    public IWebElement PasswordField;

    [FindsBy(How = How.Id, Using = "submit")]
    public IWebElement SubmitButton;

    public LoginPage(IWebDriver driver)
    {
        Driver = driver;
        PageFactory.InitElements(this, new RetryingElementLocator(Driver, TimeSpan.FromSeconds(10)));
    }

    // By this point, all your elements on the page are declared and located,
    // you're now free to carry out whatever operations you'd like on the page 
    // without having to make any further declarations

    public void Login(string username, string password)
    {
        UsernameField.SendKeys(username);
        PasswordField.SendKeys(password);
        SubmitButton.Click();
    }
}

So, I'd say it's mostly preference, but would also argue that there are some convincing arguments to be had for the "tidiness"/organisation that the @FindBy annotation brings.

Josh
  • 697
  • 7
  • 18