Please post your Web Driver questions in official Web Driver forum

Monday, November 28, 2016

How to remove duplicate page object methods

You may come across situation when you find page object methods on various classes having similar operations. For ex in following example there are two different different methods doing almost same thing. Both methods get the count of ticket in opening and outgoing queue in a system. The only difference is the element locator. One method uses element locator openingTicketCount while other uses outgoingTicketCount -

public int getOpeningTicketCount() {
   final String count = fluent(openingTicketCount).getText();
   return count.length() == 0 ? 0 : Integer.valueOf(count);
}

public int getOutgoingTicketCount() {
   final String count = fluent(outgoingTicketCount).getText();
   return count.length() == 0 ? 0 : Integer.valueOf(count);
}

We can extract the common steps and create a new private method to encapsulate them - 

private int getTicketCount(By locator) {
   final String count = fluent(locator).getText();
   return count.length() == 0 ? 0 : Integer.valueOf(count);
}

And previous page object methods can call this method with required element locator - 

public int getOpeningTicketCount() {
   return getTicketCount(openingTicketCount);
}

public int getOutgoingTicketCount() {
   return getTicketCount(outgoingTicketCount);
}

What do you think of this approach? How would you handle duplicate element locators?
Fork me on GitHub