Acceptance Tests With JBehave, Selenium & Page Objects
Since JBehave 2.0 was released in September, I've been using it on my current project to verify the acceptance criteria for the features we are implementing, ensuring that the web interface is following the right workflow, and is displaying the data as expected, as well as some other important elements.
What is JBehave?
JBehave is a framework for Behaviour-Driven Development, that allows customers and developers to work together more closely on features for the system. They get together to discuss and define a set of executable criteria (scenarios) for each of the features that will be used to determine if they are fully implemented or not. The cool thing is that the scenario execution produces an easy-to-read output, so that customers can keep track of the implementation status.
An Example
In this example, I'm not covering all the bits and pieces about writing and running acceptance tests with JBehave. If you want to see it in details, there's a very good introduction article here. The intention is to show how we are doing it on my project, integrating with Selenium and using the Page Objects pattern.
New Feature
Suppose the customer wanted to provide exclusive content for the user of the website. For that, we would have to implement an authentication framework, so that we could guarantee that only registered users would access that content. So the story looks like this:
As an user I want to login into the website So that I can view the exclusive contents
Defining Scenarios
Scenario: Invalid Username Given the user is on the login page When the user types username wrong! And the user types password 123456 And clicks the login button Then the page should display Invalid Authentication message Scenario: Successful Login Given the user is on the login page When the user types username alexandre And the user types password 123456 And clicks the login button Then the user should be redirected to home page And the page should display welcome message to alexandre
Each scenario needs its own implementation, providing the necessary steps to be verified, in our case the LoginSteps class. Another improvement on version 2.0 is that it allows you to define multiple scenarios in a single file.
public class LoginScenarios extends Scenario {
public LoginScenarios() {
super(new LoginSteps());
}
}
Defining Steps (Integrating Selenium)
After defining the scenarios on the text file, it's time to map each scenario step to its implementation. Once you start mapping them you will come across ones that are already mapped, and will realise that defining new scenarios is just a matter of combining existing steps.
Initially, for each step, we were extracting the code sniped from Selenium IDE record and placing into it. But it felt a bit clumsy, with code duplication in some spots. It quickly reminded me how hard it is to maintain a suite of tests when it starts evolve and there is not enough effort on refactoring. We wanted to avoid duplication and come up with a more elegant and reusable solution.
One day my friend Uday Rayala came up with the idea of using the Page Objects pattern for writing our acceptance tests, so that we could encapsulate the logic to interact and verify page state into these objects. The first time I heard about it was from Simon Stewart, when he was in Sydney for the JAOO conference. He said that they implemented WebDriver based on this pattern, and showed me some examples. Here is a definition, extracted from the WebDriver wikipage:
Within your web app's UI there are areas that your tests interact with. A Page Object simply models these as objects within the test code. This reduces the amount of duplicated code and means that if the UI changes, the fix need only be applied in one place.
public class LoginSteps extends Steps {
@Given("the user is on the login page")
public void theUserIsOnTheLoginPage() {
LoginPage loginPage = new LoginPage();
loginPage.verifyPresenceOfUsernameAndPasswordFields();
loginPage.verifyPresenceOfLoginButton();
}
@When("the user types username $username")
public void theUserTypesUsername(String username) {
loginPage().typeUsername(username);
}
@When("the user types password $password")
public void theUserTypesPassword(String password) {
loginPage().typePassword(password);
}
@When("clicks the login button")
public void clicksTheLoginButton() {
loginPage().login();
}
@Then("the page should display $errorMessage message")
public void thePageShouldDisplayErrorMessage(String errorMessage) {
loginPage().verifyPresenceOfErrorMessage(errorMessage);
}
@Then("the user should be redirected to home page")
public void theUserShouldBeRedirectedToHomePage() {
HomePage homePage = new HomePage();
homePage.verifyPage();
}
@Then("the page should display welcome message to $user")
public void thePageShouldDisplayWelcomeMessage(String user) {
homePage().verifyPresenceOfWelcomeMessageTo(user);
}
private LoginPage loginPage() {
return (LoginPage) Page.current();
}
private HomePage homePage() {
return (HomePage) Page.current();
}
}
Spring MVC, almost there!
One of the things I really like about Spring 2.5 is the new set of annotations for defining controllers.
Now you don't have to extend any superclass to turn your class into a controller, just add the @Controller annotation on the top of the class definition and that's it, you got one (still have to define it as a bean in the XML file). Another cool feature in this set, is the combination of the @RequestMapping and @RequestParam annotations.
@Controller
public class ProductController {
@Autowired
private MemberRepository repository;
@RequestMapping(value="/product", method=RequestMethod.GET)
public String product(@RequestParam(value="id") String id, ModelMap model) {
model.addAttribute("product", repository.getProduct(id));
return "product/view";
}
}
@RequestMapping gives you flexibility to map methods in the controller to whatever URIs and HTTP methods (default to RequestMethod.GET) you like. They are not dependent on another or on controller's name. This really turns things easier when mapping your methods to RESTful URIs. The only downside in this implementation is that it doesn't allow you to pull out parameters from an URI. If you want to grab some data from the URL, you are going to have to do it the old fashioned way, like:
mystore/product?id=123456
But on the other hand the @RequestParam annotation frees you from the dirty job of extracting parameters from a request. Thus, you don't even need to know about the HttpServletRequest and HttpServletResponse objects. To retrieve a parameter from a request, just add it as a method parameter and define it as a @RequestParam. The value attribute on the annotation should match the URL parameter name.
@RequestMapping("/products")
public String products(@RequestParam(value="letter", required=false) String letter, ModelMap model) {
checkLetter(letter);
model.addAttribute("products", repository.getProducts(letter));
return "product/list";
}
You also have the option of defining a request parameter as required or not (default set to required), so as in the example above, the method would be able to handle requests coming from both mystore/products, to list all existent products, and mystore/products?letter=A, to list all existent products starting with the letter 'A'. Really neat!
The good news is that Spring 3.0 is coming out next November, and it will include the URI templating functionality. According to Springify blog, you will be able to define a URI like mystore/product/123456, and that will map to the controller method as follows:
@RequestMapping("/product/${id}")
public String product(@RequestParam("id") String id, ModelMap model) {
model.addAttribute("product", repository.getProduct(id));
return "product/view";
}
So let's wait for it!