The Page Objects is a great pattern for automated testing of any GUI application, both desktop and web. In a nutshell the Page Object is a class that represents the page (or window for the desktop application) of the Application under the Test (AUT). The automated test interacts with the page through the page object instance.
The following example uses WebDriver, Java and TestNG and wil "test" the Google Mail login page.
First, we need to create a page object for the login page. We will use http://mail.google.com as the start page.
package demo.pageobects;
import org.openqa.selenium.RenderedWebElement; import org.openqa.selenium.WebDriver; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.pagefactory.AjaxElementLocatorFactory; public class GmailLoginPage { /** User name field*/ @FindBy (id = "Email") private RenderedWebElement userNameField;
/** Password field */ @FindBy (id = "Passwd") private RenderedWebElement passwordField; /** * Create the page object for the Gmail Login Page * * @param driver WebDriver instance */ public GmailLoginPage(WebDriver driver) { driver.get("http://mail.google.com"); PageFactory.initElements(new AjaxElementLocatorFactory(driver, 15), this); } /** * Login to Gmail as <code>username</code> with <code>password</code> * * @param username * @param password */ public void login(String username, String password) { // In case if there are previously entered values, // clear the fields userNameField.clear(); passwordField.clear(); // Type user name and password userNameField.sendKeys(username); passwordField.sendKeys(password); // Submit user name and password userNameField.submit(); } }
|
Then we will use this page object in our test class:
package demo.pageobects;
import org.openqa.selenium.WebDriver; import org.openqa.selenium.ie.InternetExplorerDriver; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test;
public class GmailLoginPageTest { private WebDriver driver; @BeforeClass public void initWebDriver() { driver = new InternetExplorerDriver(); } @AfterClass public void quitDriver() { driver.quit(); } @Test public void testLogin() { GmailLoginPage page = new GmailLoginPage(driver); page.login("user@gmail.com", "password"); }
} |
Of course this example is very simple. In your real test the login method should return the instance of another page object (i.e. InboxPage) or the new instance of the GmailLoginPage if login failed.