What is Page Object pattern? :Is the up to date smart framework as
-Easy to maintain.
-Easy readability of scripts
-Reduce or eliminate duplicity
-Re-usability of code
-Reliability
How Page Object works? : Create a separate java class for an individual page and put all the belonging objects of that page.
Ex: For Home page create a class name as ‘HomeClass’ & put all the objects locator/paths and related method (so that you can call those method from the actual Test class) of that home page inside the HomeClass. Repeat the same things for all other pages.
There are 2 types way to code or follow Page Object pattern as below:
- Regular method using By:
-Create a constructor of that class so that you can pass/initialize test driver object (which one have life) to the local driver variable what doesn’t have life.
REASON: If you need to send any argument to a class where the class not expecting any argument; then you need to create a constructor of that class.
-Start with By for Object locator (ex: By.xpath(“//*[@id=\”login1\”]”);)
-Then put object locator in a name or variable as type By
(ex: By username=By.xpath(“//*[@id=\”login1\”]”);)
-Then create a method for that object & return the object (ex: driver.findElement(username);)
Complete Example (Site: https://www.rediff.com/):
public class RediffLoginpage {
WebDriver driver;
public RediffLoginpage(WebDriver driver)
{
this.driver=driver;
}
By username=By.xpath("//*[@id=\"login1\"]");
By password=By.xpath("//input[@id='password']");
By go=By.xpath("//input[@title='Sign in']");
By home=By.linkText("Home");
public WebElement emailId()
{
return driver.findElement(username);
}
public WebElement password()
{
return driver.findElement(password);
}
public WebElement submit()
{
return driver.findElement(go);
}
public WebElement home()
{
return driver.findElement(home);
}
}
- Factory Page Method:
-Create a constructor of that class so that you can pass/ initialize test driver to local driver (which doesn’t have life).
-After then Add the following code inside constructor for Factory page style
PageFactory.initElements(driver, this;
-Start with @FindBy then Object locator
@FindBy (xpath=”//u[contains(text(),’Money’)]”)
-Then put object locator in a name or variable as type WebElement
@FindBy (xpath=”//u[contains(text(),’Money’)]”)
WebElement money;
-Then create a method for that object & return the object (ex:
public WebElement moneyLink ()
{
return money;
}
Complete Example:
public class RediffHomepageFactoryStyle {
WebDriver driver;
public RediffHomepageFactoryStyle(WebDriver driver)
{
this.driver=driver;
//Need to add the below line for FactoryPage style
PageFactory.initElements(driver, this);
}
@FindBy (xpath="//u[contains(text(),'Money')]")
WebElement money;
public WebElement moneyLink ()
{
return money;
}
}