Question

I'm new to java Selenium WebDriver programming and automation.

Can anyone explain page object pattern with example.

No correct solution

OTHER TIPS

PageObject pattern represents the screens (pages) of your web app as a series of objects (java classes). These objects are called "PageObjects"

A PageObject need not represent an entire page. It may represent a section that appears many times within a site or page, such as site navigation. The essential principle is that there is only one place in your test suite with knowledge of the structure of the HTML of a particular (part of a) page.

For example, instead of having a test method like this:

@Test()
public void test() {
    driver.get("http://www.mysite.com");
    WebElement username = driver.findElement(By.id("user"));
    username.sendKeys("admin");
    WebElement password = driver.findElement(By.id("pass"));
    password.sendKeys("admin");
    WebElement login = driver.findElement(By.id("login"));
    login.click();
    // ...
}

where you will be redefining the WebElements username, password and login if you have to create another test for the login page, you can use a PageObject to represent the login page like this:

public class LoginPage {
public HomePage loginAs(String username, String password) {
    WebElement username = driver.findElement(By.id("user"));
    username.sendKeys("admin");
    WebElement password = driver.findElement(By.id("pass"));
    password.sendKeys("admin");
    WebElement login = driver.findElement(By.id("login"));
    login.click();
    return new HomePage();
}

and then, from your test:

@Test()
public void test() {
    driver.get("http://www.mysite.com");
    LoginPage loginPage = new LoginPage();
    HomePage homePage = loginPage.loginAs("admin", "admin");
    // ...
}

Anyway, I would recommend you to take a look at the official documentation of PageObjects and also to read about PageFactory.

Hope this helps ;)

I think the best place to learn it, and by example is in Selenium Project page in Google Code.

Understand the concept first - Every page is represented by a class, and experiment on a simple website you already familiar with.

For example, choose a simple website and write some tests to verify the login process. Do so by modeling the participating web pages(ex. LoginPage, HomePage) in classes as specified in the Page Objects design pattern, and use those objects in the test methods.

When you feel comfortable enough with it, you can take it a step forward and for complex web pages, model a separate class for different sections on a single page for better re-usability and less maintenance overhead.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top