How to Implement Page Object and Page Factory Pattern in Selenium Webdriver?



  • I am a beginner in learning selenium Webdriver. I am not able to understand how page object and factory models works and how it can be beneficial? Kindly help me explain it with detailed explanation.



  • 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(WebDriver 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 https://github.com/SeleniumHQ/selenium/wiki/PageFactory https://github.com/SeleniumHQ/selenium/wiki/PageObjects https://github.com/SeleniumHQ/selenium/wiki/Design-Patterns



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2