The chief problem with script maintenance is that if 10 different scripts are using the same page element, with any change in that element, you need to change all 10 scripts. This is time consuming and error prone.
A better approach to script maintenance is to create a separate class file which would find web elements, fill them or verify them. This class can be reused in all the scripts using that element. In future if there is change in the web element, we need to make change in just 1 class file and not 10 different scripts.
This approach is called Page Object Model (POM). It helps make code more readable, maintainable, and reusable. POM is an object design pattern in Selenium, where web pages are represented as classes, and the various elements on the page are defined as variables on the class. All possible user interactions can then be implemented as methods on the class. Since well-named methods in classes are easy to read, this works as an elegant way to implement test routines that are both readable and easier to maintain or update in the future.
Advantages of using Page Object Model:
1. Easy to Maintain
2. Easy Readability of scripts
3. Reduce or Eliminate duplicity
4. Re-usability of code
5. Reliability
6. Code becomes optimized
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; public class pomExample { /* * I will be listing By methods (without using pageFactory) that I have used * For some methods I am using gmail example. */ WebDriver driver; By un=By.id("Email"); By next = By.name("signIn"); By pw = By.xpath(".//*[@id='Passwd']"); By signInButton = By.className("gmail-nav__nav-link gmail-nav__nav-link__sign-in"); By byCssSelector = By.cssSelector("some css selector"); By byLinkText = By.linkText("some linkText"); By byPartialLinkText = By.partialLinkText("some partial linkText"); By byTagName = By.tagName("some tag name"); Class<By> byClass = By.class; // Now we will create a constructor to call this reusable class public pomExample(WebDriver driver){ this.driver=driver; } // New we will create some sample reusable methods using gmail login page public void clickSignIn(){ driver.findElement(signInButton).click(); } public void enterUserName(){ driver.findElement(un).clear(); driver.findElement(un).sendKeys("username"); } public void clickNext(){ driver.findElement(next).click(); } public void enterpwd(){ driver.findElement(pw).clear(); driver.findElement(pw).sendKeys("password"); } } |
And you can reuse these POM classes like so:
1 2 3 4 5 6 7 8 9 10 11 12 13 | // Sample to call the reusable pom class (non pageFactory) @Test public void pomLoginSample() { driver.get("https://www.gmail.com"); pomExample login = new pomExample(driver); login.clickSignIn(); login.enterUserName(); login.clickNext(); login.enterpwd(); } |
No comments:
Post a Comment