Search code examples
webdriverselenium-webdriverui-automationabstractionpageobjects

Ideal way to model elements on a web page as classes in WebDriver for abstraction and re-use


What could be the ideal way to model the elements on a webpage as classes for the sake of abstraction and re-usability?
Currently, what I have created is a BaseElement.java class that contains the following member variables:

WebDriver webdriver;

The constructor:

protected BaseElement(WebDriver driver)
 {
  //Initialization.
 }

I am then extending this class in other classes which represent a certain element on the webpage.
For example, I have a Button.java class which extends BaseElement.java.

  public class ButtonElement extends BaseElement {


        String locator;
        By by;
        WebElement button;

        protected ButtonElement(WebDriver driver, String locator, By by) {
            super(driver);
            this.by = by;
            this.locator = locator;

           //code to find the element using driver.findElement()
           // I am not sure how to use By in here depending upon what I pass in the constructor when I create an object of this class. Any suggestions?
        }

        public void click() {

          button.click();
        }

        //Other methods which will interact with the element in other ways.
  }

So, in my PageObject classes, I will make use of the above like:

Button loginButton = new Button(driver,"btn-Login",By.id);
loginButton.click();

Is this the right approach? Is there any better way to abstract, hide complicated logic in a single class, and reuse the elements like button, textbox, select list etc from a webdriver perspective?? Thanks in advance!


Solution

  • I don't believe passing in the driver each time you locate an element is the way to go, but I understand you are aiming to avoid repeating code. You could instead have a class that accesses a driver class, which is instantiated at the start of your code. This way you can pass in a 'type' and 'attribute' which will locate any implemented element. eg. Type: Id, Class, XPath; and Attribute: "text", "//div[@class="class"]/div[2]".

    So,
    DriverClass: Has a WebDriver that implements FindElement with a switch for each type.
    WrapperClass: Which has classes such as 'Click' or 'DoesElementExist' which uses DriverClass to implement functionality.
    TestClass: Using calls to WrapperClass implements your code logic.

    You could go further and implement common groupings of actions in another class that utilises WrapperClass so TestClass becomes a lot cleaner.