TesterHQ - The Evil Tester Blog Aggregator

Aug 17, 2013 - 2 minute read - Practices Selenium Simplified Blog WebDriver

A Fluent Page Object Approach - return this

Original Blog Posting on [SeleniumSimplified.com]

Another simple tip, but I use this a lot.

Return ‘this’ from your Page Object methods

 

e.g.

QueNessSlowLoadingExamplePage page4 = 
       new QueNessSlowLoadingExamplePage(driver);
 page4.get();

page4.
 setName("Bob Dobbs").
 setEmail("b.dobbs@mailinator.com").
 setMessage("Hello There").
 sendMessage();

In the above code I have a Page Object called QueNessSlowLoadingExamplePage which handles this example over at QueNess.com

And you can see that the setName, setEmail and setMessage are all ‘fluent’ in the sense that they return ‘this’ so I can chain them when using the Page Object.

e.g.

public QueNessSlowLoadingExamplePage setName(String name) {
 driver.findElement(NAME_FIELD).sendKeys(name);
 return this;
}

public QueNessSlowLoadingExamplePage setEmail(String email) {
 driver.findElement(EMAIL_FIELD).sendKeys(email);
}

On returning ‘other’ Page Objects

Note that this does not mean that I advocate returning ‘other’ Page Objects from a Page Object

i..e if ‘sendMessage’ causes a chain of system events such that a new page is displayed in the browser then I don’t advocate returning that page as a Page Object from the ‘sendMessage’ object.

If navigating to a new page was a possibility I would make ‘sendMessage’ a ‘void’ object, because I treat ‘Navigation’ as a separate responsibility, managed by a separate set of Objects.

On returning child components

Note that this does not mean that I never return ‘child’ or ‘container’ Page Objects.

e.g. if this page had a Widget, that I had modelled as a separate Page Object, I am quite happy to return a ‘new Widget’ Object from a method on this Page Object, because this Page Object would be acting as a container for that one.

Not an absolute rule

But not navigation.

Not for me.

At least, most of the time, because all rules are made to be broken, thereby granting us the requisite variety we need to model our applications effectively. So sometimes I may choose to navigate via Page Objects. Very often I do this for expediency, or for throw away code. I’ll very likely refactor it out later.

You can find code that illustrates this on github in my WebDriverExperiments repository.

Is this what you do?

Is this what you do? Leave a comment if you have any other Page Object Method tips.