Starting out with page objects

Let's take goToTheAboutPage() as an example. We have refactored it to make it nice and clear, but we now want to abstract things away into a page object to encourage other people to use all that hard work finding the correct locators. Let's create two page objects called IndexPage and AboutPage and move our element definitions across into them. We will start off with the index page:

package com.masteringselenium.page_objects;

import org.openqa.selenium.By;

public class IndexPage {

public static By heading = By.cssSelector("h1");
public static By mainText = By.cssSelector(".col-md-4 > p");
public static By button = By.cssSelector(".btn");
public static By aboutLinkLocator =
By.cssSelector(".left-footer > a");
}

Then, we need to create the page object for the about page:

package com.masteringselenium.page_objects;

import org.openqa.selenium.By;

public class AboutPage {

public static By heading = By.cssSelector("h1");
public static By aboutUsText = By.cssSelector(".col-md-4 > p");
public static By aboutHeadingLocator = By.cssSelector("h1");
}

You may have noticed that we added a few more locators to the IndexPage and AboutPage objects. Page objects are a codified representation of a page, so it's fine to add some information about elements that we don't use yet. This information will be used later on in this chapter, but we don’t need to worry about this for now. Next, we need to modify the goToTheAboutPage() test to use the page objects:

@Test
public void goToTheAboutPage() {
driver.get("http://web.masteringselenium.com/index.html");

WebElement aboutLink =
driver.findElement(IndexPage.aboutLinkLocator);

aboutLink.click();

WebElement aboutHeading =
driver.findElement(AboutPage.aboutHeadingLocator);

assertThat(aboutHeading.getText()).isEqualTo("About us!");
}

Excellent, we are now using our page objects and have a series of element definitions that can be reused, but we still have a couple of issues.

First of all; we have put our page object in with our tests:

It may seem like a good idea at first, but when you have a mature product with quite a few tests, you will find that it will start to become hard to find your page objects. So, what should we do? We will follow good programming practices and keep our page objects separate, to ensure that we have a good separation of concerns.

Let's create a place for our page objects to live that is separate from the tests and has a sensible name that will indicate to people what these pieces of code are:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.89.85