Friday, July 20, 2018

PageObejctModel in Selenium WebDriver

Page object model is a wonderful design pattern to abstract out Web Page elements and its actions from actual tests. We can use this way to build a test framework of the project and focus on business only in all the test cases.

Here is a demo for page object model.


package me.simplejavautomation.pages;

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

public class PercentageCalculatorPage {

    @FindBy(id = "A")
    private WebElement a;

    @FindBy(id = "B")
    private WebElement b;

    @FindBy(id = "C")
    private WebElement c;

    public WebElement getA() {
        return a;
    }

    public void setA(WebElement a) {
        this.a = a;
    }

    public WebElement getB() {
        return b;
    }

    public void setB(WebElement b) {
        this.b = b;
    }

    public WebElement getC() {
        return c;
    }

    public void setC(WebElement c) {
        this.c = c;
    }

}

package me.simplejavautomation;

import static org.junit.Assert.assertEquals;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.PageFactory;

import me.simplejavautomation.pages.PercentageCalculatorPage;

public class PageObjectTest {

    private WebDriver driver;

    @Before
    public void setUp() {
        driver = new ChromeDriver();
    }

    @After
    public void tearDown() {
        driver.quit();
    }

    @Test
    public void testPercentageCalculation() {
        // open http://www.percentagecalculator.co/ web site
        driver.get("http://www.percentagecalculator.co/");

        PercentageCalculatorPage pageObject = PageFactory
            .initElements(driver, PercentageCalculatorPage.class);
        pageObject.getA().sendKeys("10");
        pageObject.getB().sendKeys("100");

        assertEquals("10", pageObject.getC().getAttribute("value"));
    }

}

No comments:

Post a Comment