Saturday, 26 March 2016

Page Factory Model in Selenium Automation

There are several automation frameworks as described @softpost.org. Page Factory model is one of the most popular selenium automation framework.

Key features of Page Factory model

  1. Object oriented
  2. Most of the features are similar to Page Object Models
  3. One primary difference between page object model and page factory model is that web elements are initialized in different manner.

Here is the sample Page class for a page @Softpost.org

package pages;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import pages.common.BasePage;

public class SeleniumTestPageUsingFactory extends BasePage {

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

    @FindBy(id = "fn" )
    WebElement firstName;

    public void setFirstName(String name){
        firstName.sendKeys(name);
    }

    public String getFirstName(){
        return firstName.getAttribute("value");
    }

}

Note how we have used PageFactory.initElements method to initialize the elements on the page.

We can instantiate this page class and perform operations on Page elements. Below class demonstrates how we can use this Page class in tests.

package page_object_model_tests;

import org.junit.Assert;
import org.junit.Test;
import page_object_model_tests.BaseTests.BaseTest;
import pages.SeleniumTestPage;
import pages.SeleniumTestPageUsingFactory;

public class SamplePageTestsUsingFactory extends BaseTest {

    @Test    public void testPage() {
     SeleniumTestPageUsingFactory seleniumTestPage;
     seleniumTestPage  = new SeleniumTestPageUsingFactory(driver);
     seleniumTestPage.setFirstName("Sagar");
     String name = seleniumTestPage.getFirstName();
     Assert.assertTrue("Name validation",name.equalsIgnoreCase("Sagar"));
    }
}

What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

No comments:

Post a Comment

Buy Best Selenium Books

About Me

My photo

Self-motivated software professional