Friday, March 18, 2016

Selenium : Page Object Model (By) VS Page Factory (@FindBy)


 Page Object Model (By) VS Page Factory (@FindBy)


1) Page Object Model

- Page Object Model - Initialize all object locators separately using "By"

 Code Here :
class starttest{
     @Test
      public void LoginTest() {    
            By usernameField = By.xpath("//*[text()=login_login_username]")
            By passwordField = By.name("//*[text()=login_login_password]")
            By loginButton = By.xpath("//*[text()=login_submit]");
          
            WebDriver driver=new FireFoxDriver();
            driver.get("http://some-login-page");
          
            driver.findElement(usernameField).sendKeys("my name");
            driver.findElement(passwordField).sendKeys("my password");
            driver.findElement(loginButton).click();
      }
  }

 2) Page Factory (@FindBy and PageFactory.initElements(driver, .class))

 1) @FindBy can accept tagName, partialLinkText, name, linkText, id, css, className, xpath as attributes.

2)  @FindBy(xpath="//*[text()=login_login_username]")
    private WebElement usernameField;
 

Is  Same as 

WebElement usernameField=By.xpath("//*[text()=login_login_username]")

3)
  @FindBy(xpath="//*[@id='']")    is same as     //@FindBy(how = How.xpath, using ="//*[@id='']")
 @FindBy(name="username")        is same as     //@FindBy(how = How.NAME, using = "username")
 @FindBy(className="radio")       is same as       //@FindBy(how = How.CLASSNAME, using = "radio")

 Code Here :


class starttest{

     @Test
      public void LoginTest() {   
        WebDriver driver=new FireFoxDriver();
        driver.get("http://some-login-page");
       
        LoginPage loginPage=PageFactory.initElements(driver, LoginPage.class); //Initialize Login Page     
        loginPage.login("student1","Testing1");
      }
  }


 public class LoginPage {

    @FindBy(xpath="//*[text()=login_login_username]")
    private WebElement usernameField;   \\
By usernameField = By.xpath("//*[text()=login_login_username]")   
   

 @FindBy(xpath="//*[text()=login_login_password]")
    private WebElement passwordField;   
   
    @FindBy(xpath="//*[text()=login_submit]")
    private WebElement loginButton;        

   
    public void login(String usernametext,String passwordtext)    {
        usernameField.sendKeys(usernametext);
        passwordField.sendKeys(passwordtext);
        loginButton.click();
    }   
}

No comments:

Post a Comment