PageObjects
The code of automated test cases should be easy to understand and not too complex. If a test fails, we want to know why and this as soon as possible. To allow this exists PageObjects. PageObjects are classes that contains WebElements and every actions associated with those.
A PageObject looks like this:
class HomePage {
WebDriver driver;
public HomePage(driver) {
this.driver = driver;
}
// Find a single element
@FindBy(id="home-menu-entry")
WebElement homeMenuEntry;
public void clickHomeMenuEntry() {
homeMenuEntry.click();
}
// Find several elements
@FindBy(className="menu-entry")
List<WebElement> menuEntries;
// More actions and elements
}
Usage of PageFactory and PageObject
class TestSomething {
public void testMethod() {
// Initial driver.
// Use PageFactory to init elements.
HomePage hp = PageFactory.initElements(driver, HomePage.class);
// Use PageObject to execute action.
hp.clickHomeMenuEntry();
// Assertions or more actions.
}
}
You also can put the
PageFactory.initElements();
into the constructor and create just an HomePage
object instead of calling the PageFactory
method.
Important: If you call
initElements()
all elements will be initialized, not later if you use them.
How to organize this?
I do the following: Each page has a PageObject, that represent these. But some components of a page are present on many pages. For this case I create for each component additional classes. Example:
- Header.class
- Footer.class
- HomePage.class
- ContactPage.class
Useful Links
No comments:
Post a Comment