Wednesday, October 5, 2011

Selenium PageObject

PageObject

• PageObjects is a design pattern where objects representing your pages are exposed to the
test logic as services providing access to the elements and logic of your page
• The pattern is defined along the following:
o The public methods exposes the services the page offers
o The internals of the page should not be exposed
o Don’t make assertions in the PageObject class, it is the test logic’s work
o Methods return other PageObjects
o You don’t need to represent an entire page, just the services you need to test
o One action can have several methods depending on the result of these actions
• PageObjects' methods exposes actions on the page (a login action for instance) and must return another PageObject:


class LoginPage
@error_message
//Once logged-in, the server redirects to the home page so the login methods should return a PageObject representing the homepage
def loginAs(username, password)
# ...
HomePage.new
end

//We test a failed login gives the correct message. Since it is a failed login, we stay on the login page so we return the same object
def loginAsExpectingError(username, password)
# ...
# error_message = something
self
end
def error_message
@error_message
//We can return here the error message displayed on the page in case of failed login
end



public class LoginPage {
private String errorMessage;
//Once logged-in, the server redirects to the home page so the login methods should return a PageObject representing the homepage

public HomePage loginAs(username, password) {
...
return new HomePage();
}
public LoginPage loginAsExpectingError(username, password) {
//We test a failed login gives the correct message. Since it is a failed login, we stay on the login page so we return the same object

...
errorMessage = something;
return self;
}

public void getErrorMessage() {
return errorMessage;
//We can return here the error message displayed on the page in case of failed login
}
}



• The PageObject pattern is a good practice because:
- It facilitates code reuse: think about inheritance and abstract classes
- It facilitates maintenance: code logic and page are separated



PageObject Pattern
We’re going to transform our tests to follow the PageObject pattern
Java
• You will find in the project in the labs/lab6/java folder a Page class as well as a Lab6 containing the test to run
• The Page class is the class from which all your projects will inherit from
• The Lab6 class contains the test and therefore, the methods to implement in your page objects

1 comment: