Think of methods in PageObjects as services and not as user actions

There might sometimes be confusion surrounding what methods make a PageObject. We saw earlier that each PageObject should contain User Services as their methods. But quite often, we see some implementations of PageObjects in several test frameworks that constitute User Actions as their methods. So what is the difference between a User Service and a User Action? As we have already seen, some of the examples of User Services on the WordPress Admin console are as follows:

All the preceding services talk about the various functionalities of the target application. Now, let's see some examples of User Actions:

The previous list showed some examples of User Actions on a page. They are common across many applications. Your PageObject is not meant to provide your test case with User Actions, but with User Services. So, each method in your PageObject should map to a service that the target page provides to the user. To accomplish a User Service, PageObject methods should contain many User Actions.

Several User Actions come together to accomplish a User Service.

Here is an example of what your PageObject will look like if it provisions its methods with User Actions instead of User Services is as follows; let's see what the AddNewPage PageObject will look like:

public class AddNewPost {

WebDriver driver;

@FindBy(id = "content_ifr")
WebElement newPostContentFrame;

@FindBy(id = "tinymce")
WebElement newPostContentBody;

@FindBy(id = "title")
WebElement newPostTitle;

@FindBy(id = "publish")
WebElement newPostPublish;

public AddNewPost(WebDriver driver) {
this.driver = driver;
System.out.println(driver.getCurrentUrl());
}

public void typeTextinTitle(String title) {
newPostTitle.sendKeys(title);
}

public void clickPublishButton() {
newPostPublish.click();
}

public void typeTextinContent(String descContent) {
driver.switchTo().frame(newPostContentFrame);
newPostContentBody.sendKeys(descContent);
}
}

So, in the code of the AddNewPage PageObject, we have three different methods to accomplish three different User Actions. The caller object, instead of just invoking the addNewPage(String title, String description) method, should now invoke the following:

typeTextinTitle(String title)
typeTextinContent(String description)
clickPublishButton()

The preceding User Actions are three different User Actions to accomplish adding a new post User Service. The caller of these methods should also keep in mind the order in which these User Actions need to be called; that is, the clickPublishButton() method should always come last. This introduces unnecessary complexity to your test cases and other PageObjects that try to add new posts to the system. Thus, User Services will hide most of the implementation details from the users of the PageObjects and reduce the cost of maintaining your test cases.