Checkout our demo site to practice selenium https://magento.softwaretestingboard.com/

1 like 0 dislike
289 views
in Selenium by The go-to Tester (391 points)
retagged by
Could you please explain Page Object Model and Page Factory with an easy example?

1 Answer

0 like 0 dislike
by The go-to Tester (181 points)

See below code snippest. Its an example of page object model. You will have all elements manually defined and elements will be indetified on demand.

 

 
public class GmailLoginPage {
  private final WebDriver driver;
//Page Object constructor which passes the driver context forward
  public LoginPage(WebDriver driver) {
      this.driver = driver;
  }
  By usernameloc = By.id("Email");
  By passwordloc = By.id("Passwd");
  By loginButtonloc = By.id("signIn");
 
  public HomePage LoginToGmailAsValidUser(String username, String password) {
    driver.findElement(usernameloc ).sendKeys(username);
driver.findElement(passwordloc ).sendKeys(password);
driver.findElement(loginButtonloc   ).click();
    return new InboxPage(driver) 
  }
  public GmailLoginPage LoginToGmailAsInvalidUser(String username, String password) {
    driver.findElement(usernameloc ).sendKeys(username);
driver.findElement(passwordloc ).sendKeys(password);
driver.findElement(loginButtonloc   ).click();
    return this;
  }
}
 
 

 

Here is sample of PageFactory class.

import org.openqa.selenium.By;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
import org.openqa.selenium.WebElement;

public class GoogleSearchPage {
    // The element is now looked up using the name attribute
    @FindBy(how = How.NAME, using = "q")
    private WebElement searchBox;

    public void searchFor(String text) {
        // We continue using the element just as before
        searchBox.sendKeys(text);
        searchBox.submit();
    }
} 

 

In page factory elements are initiated as soon as class initiated.


This site is for software testing professionals, where you can ask all your questions and get answers from 1300+ masters of the profession. Click here to submit yours now!

1.4k questions

1.6k answers

866 comments

1.9k users

...