Tuesday, 13 May 2014

Limitation of Using @FindBy Annotation In PageFactory And How to overcome it

Example Of PageFactory:
import org.openqa.selenium.WebDriver
import org.openqa.selenium.WebElement
import org.openqa.selenium.support.PageFactory

////PageLogin.java
public class PageLogin
{
   @FindBy(id="userName")
   private WebElement PageLogin_txtUserName;
   @FindBy(id="password")
   private WebElement PageLogin_txtPassword;
   @FindBy(id="btnSubmit")
   private WebElement PageLogin_btnSubmit;

 //instance initialization block
{
//pseudo singleton method to retrieve WebDriver Instance
WebDriver wd=WebDriverInstance.getWebDriverInstance();
wd.get("http://localhost:8080/Project/login.html);
PageFactory.initElements(wd,this);
}
//instance initialization block ends
public String doLogin(String userName,String password)
{
   PageLogin_txtUserName.sendKeys(userName);
   PageLogin_txtPassword.sendKeys(password);
   PageLogin_btnSubmit.click();

   return WebDriverInstance.getWebDriverInstance().getTitle();

}

}
//class definition PageLogin.java ends
////testLogin.java
PageLogin login=new PageLogin();
login.doLogin("A","B");  //#1
login.doLogin("C","D"); //#2
In step #1 and #2, driver will look for userName and password every time on page, when ever we call login.doLogin, which will degrade the performance.
The solution should be once userName/password is found/located, it should be stored in memory.
PageFactory provides this solution. @CacheLookup is solution.
So, above code can be enhanced to
@FindBy(id="userName")
@CacheLookup
   private WebElement PageLogin_txtUserName;
@FindBy(id="password")
@CacheLookup
   private WebElement PageLogin_txtPassword;
@FindBy(id="btnSubmit")
@CacheLookup
   private WebElement PageLogin_btnSubmit;

This will result locators(Referred WebElements) to be cached.

No comments:

Post a Comment