Encapsulation and using getter/setter methods to retrieve objects from the page object classes

The first Selenium page object class was created containing two getter and two setter methods. These methods, although not entirely object-oriented, are required to provide a way for the Selenium test classes to access a component inside the page object instance. This is a basic concept in Java called encapsulation. The data variables and objects in the class are hidden by making them private or protected, and only accessible outside the class using the getter methods, and so on.

As a general rule, we want to keep a separation between the page object and test classes. So, what happens if the user needs to access a button on the page to cancel some action or dialog from within the test class? They only have two choices: call the WebDriver class's findBy method and pass in a dynamic locator to access the object, or create a method to get the static WebElement on the page.

Of course, we do not want to start adding locators to the test classes - this would violate the page object Model we are following to separate the page object and test classes. It also lends to the idea that we would have the same locator in two places: the page object and test class. If we do this over and over, the maintenance level increases dramatically. When the locators change, then the change needs to be implemented in multiple places, and so on.

There is a Java tutorial on encapsulation and the use of getter/setter methods located at https://www.tutorialspoint.com/java/java_encapsulation.htm.

So, the getter methods can return a variable, WebElement, MobileElement, or String. They can be useful in test classes that need to access a page object element, or in another class that is instantiating it. Finally, let's look at an example of a getter method that returns a WebElement:

// cancel button in Page Object class

public class MyPageObject {
...

@FindBy(id= "Cancel")
@CacheLookup
protected M cancel;

// getter method in Page Object class

/**
* getCancel method
*
* @return WebElement
* @throws Exception
*/
public M getCancel() throws Exception {
return cancel;
}
}


// getCancel method call on instance of class in Test Method

public void tc001_myTestcase() {
...

MyPageObject pageObj = new MyPageObject();
pageObj.getCancel();

...
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.150.89