Selenium Page Objects
Selenium Page Objects
In this post, you will learn Selenium Page Objects, the most important aspect of authoring real-time web application tests using Selenium Webdriver.
What is a Page object?
We use A page object to represent an HTML page and its elements to abstract them in our Selenium tests. So, our Selenium tests will not interact with HTML code directly but with page objects that use selectors to refer to the HTML code. We may create independent classes to declare our page objects. The class should group together all the page objects on the same page. The tests and page objects should be independent of the other.
Let us build a sample PageObject for a Login page below:
package com.testingdocs.testng.sample; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; public class LoginPage { private final WebDriver driver; private By username = By.id("userID"); private By password = By.id("pwd"); private By loginSubmit = By.id("submit"); public LoginPage(WebDriver driver) { this.driver = driver; } public LoginPage typeUserID(String userID) { driver.findElement(username).sendKeys(userID); return this; } public LoginPage typePassword(String pass) { driver.findElement(password).sendKeys(pass); return this; } public void submitLogin() { driver.findElement(loginSubmit).submit(); } public void login(String userID, String password) { typeUserID(userID); typePassword(password); } }
Now a sample test which instantiates the page object with out the knowledge of html elements and the locating mechanism of the login elements.
package com.testingdocs.testng.sample; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.annotations.Test; public class SampleLoginTest { WebDriver driver = new FirefoxDriver(); LoginPage lpage = new LoginPage(driver) ; @Test public void logintest() { driver.get("Sample_Login_Page_URL"); lpage.login("1001", "mypassword1234$"); ..... ..... } }
Advantages of Page object
Firstly, we can take advantage of object-oriented approaches like abstraction, encapsulation, etc by using page objects.
Shield tests against application HTML code changes. Changes will only affect the page object andĀ not our selenium tests
Using page objects we will avoiding redundant code.
We can have page objects in only one place and refer to them in our tests.
PageObject may need not represent an entire page. It may represent a section that appears many times within a site or page. The motto is that there is only one place in your entire test suite with knowledge of the structure of the HTML of a particular page or part of it. In conclusion, using page objects we can write robust web tests without worrying about the HTML web page changes.
Selenium WebDriver Tutorials on this website can be found at: