Archive for the ‘Behaviour-Driven Development’ tag
Hamcrest Out Of Test Code!
It’s been a while since I read some interesting posts showing creative uses of Hamcrest library out of test code. Since then I’ve been proscrastinating to implement my own version, trying strongly typed java delegates.
Thankfully this week I came across a nice API called hamcrest-collections. It uses Hamcrest to implement features such as select, reject, map, reduce and zip familiar from languages like Ruby and Python.
Selectors
Selectors can be used to select or reject items that matches a given Matcher, from any iterable object. It reminds me the Specification Pattern from Domain-Driven Design, which is also used for querying objects that satisfies defined specifications.
public static final Person john = new Person("John", 28);
public static final Person nicole = new Person("Nicole", 12);
public static final Person ryan = new Person("Ryan", 23);
public static final Person nathan = new Person("Nathan", 18);
public static final List list() {
return Arrays.asList(john, nicole, ryan, nathan);
}
The code below selects from the list of users defined above, the ones that are under twenty.
@Test
public void should_select_only_people_under_twenty_years_old() {
List users = Person.list();
Iterable underTwentyList = select(users, underAge(20));
assertThat(underTwentyList, hasItems(nicole, nathan));
assertThat(underTwentyList, not(hasItems(john, ryan)));
}
The code below rejects all the users that are under twenty.
@Test
public void should_reject_every_people_under_twenty_years_old() {
List users = Person.list();
Iterable aboveTwentyList = reject(users, underAge(20));
assertThat(aboveTwentyList, hasItems(john, ryan));
assertThat(aboveTwentyList, not(hasItems(nicole, nathan)));
}
Map and Reduce
Map is used to apply a function onto each item in any iterable object, whereas Reduce combines all these elements, applying a Reducer implementation. In our example, we map the timesTwo function, that doubles each element in the list, and then we reduce it by adding up all of them.
@Test
public void should_double_each_number_in_the_list_then_sum_all_of_them() {
List numbers = Arrays.asList(1, 2, 3);
MultiplyBy timesTwo = new MultiplyBy(2);
Iterable result = map(numbers, timesTwo);
assertThat(result, hasItems(2, 4, 6));
Integer sum = reduce(result, new Sum());
assertThat(sum, equalTo(12));
}
public class MultiplyBy implements Function{ private Integer factor; public MultiplyBy(Integer factor) { this.factor = factor; } public Integer apply(Integer number) { return (int)number * factor; } }
public class Sum implements Reducer{ public Integer apply(Integer first, Integer second) { return first + second; } }
Despite the bias created by some developers, that Hamcrest should not be used anywhere else but test code, specially after JUnit has defined it as its new matcher library, just ignore it and add these features to your runtime library, so that you can let your creativity drive you when developing. Get rid of “for” loops from your life! ![]()
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();
}
}
First Sydney Coding Dojo
Last Wednesday, 5th of November, we run our first Coding Dojo session at Sydney office. We had a reasonable number of attendants, and the experience was fantastic, although we still have some points to improve.
The Initiative
The idea was originally from my friend and flat-mate Mark Needham. Since we moved in to our new place, he came up with the idea of getting together every week to solve some CodeKatas at home, exploring a different language. We decided it would be more interesting if we could broaden the idea, and decided to organise a session at the Community College in the ThoughtWorks office.
How did we run:
There were six people attending, so we decided to split it into three pairs, each with their own solution, rotating every ten minutes.
We had three design discussion breaks, one in the beginning, one in the middle and another at the end of the session. Since the focus was on object-oriented design, we chose to implement the bowling game, extracted from Uncle Bob Martin’s book. We did it following the Object Calisthenics rules, which are:
- Use only one level of indentation per method
- Don’t use the else keyword
- Wrap all primitives and strings (strong types)
- Use only one dot per line
- Don’t abbreviate
- Keep all entities small
- Don’t use any classes with more than two instance variables
- Use first-class collections
- Don’t use any getters/setters/properties
What was cool:
Apart from being an amusing experience, it was quite interesting to see the different approaches that people take to solve the same problem, - the design, the way they write tests, the code style, pretty cool. The pair swapping was also another nice experience. It was gratifying to pair with ThoughtWorkers other than the ones on my current project, like David Cameron and Nick Carroll.
Future improvements:
For the next session, I would like to experiment with another approach.
Restrict the number participants from seven to ten developers. And instead of splitting them into as many pairs as possible, having all seated around a table, where there would be only one pair working on the solution, while the others are watching through a projector. They are free to help whenever they want, providing suggestions, ideas for design, algorithm, etc. The developers pairing would be swapped every ten minutes, by other ones participating. Although the number of developers participating is restricted, anyone is welcome to attend as a watcher.
I reckon we would be much more productive this way, when everyone is working on the same thing, centralizing the focus, and learning even more from other developers.
JBehave Matchers
JBehave and JMock2 are tools I’ve been using on my latest projects to define the behaviours of my objects. Both, when used together supplies pretty much all the resources needed to write effective behaviour verification. But in this topic I’m going to talk about JBehave Matchers.
Matchers are handy objects, inspired by JUnit Assert class, but much more elaborated. They can help us in loads of scenarios, without the need to write repeated code, such as loops, ifs, elses, turning out the code cleaner and much more intuitive. Currently there are six matcher subtypes: UsingArrayMatchers, UsingCollectionMatchers, UsingEqualityMatchers, UsingExceptions, UsingLogicalMatchers e UsingStringMatchers. For now, I’m just going to talk about four of them, which for me are the most innovative ones.
UsingArrayMatchers e UsingCollectionMatchers
Both are quite similar in their behaviours, the only thing that distinguishes them, as their names indicates, is the object on which operations are executed upon. I decided using the UsingArrayMatchers matcher to show some examples of features it comprises:
1 - Check if a Collection/Array contains a certain object:
Integer[] array = new Integer[] {3};
Ensure.that(array, contains(3));
Ensure.that(array, not(contains(5)c));
2 - Check if a Collection/Array contains a certain set of objects:
Integer[] array = new Integer[] {3, 4, 5};
Ensure.that(array, contains(3, 4));
Ensure.that(array, contains(3, 4, 5));
3 - Check if a Collection/Array contains only a certain set of objects, and nothing more:
Integer[] array = new Integer[] {3, 4, 5};
Ensure.that(array, containsOnly(3, 4, 5));
Ensure.that(array, not(containsOnly(3, 4)));
4 - Check if a Collection/Array contains a certain set of objects, in a defined order:
Integer[] array = new Integer[] {3, 4, 5};
Ensure.that(array, containsInOrder(3, 4, 5));
Ensure.that(array, not(containsInOrder(4, 5, 3)));
UsingStringMatchers
The methods in this class are self-explanatory, just check it out:
Ensure.that("octopus", contains("top"));
Ensure.that("octopus", not(contains("pee")));
Ensure.that("octopus", startsWith("octo"));
Ensure.that("octopus", not(startsWith("pee")));
Ensure.that("octopus", endsWith("pus"));
Ensure.that("octopus", not(endsWith("pee")));
UsingLogicalMatchers
Using this class, it’s possible to negate any matcher and define matcher compositions using AND, OR, EITHER, BOTH. This class for me is the most powerful one, it gives us a wide range of interesting possibilities. Let’s try some of them, so you can see how far you can go.
1 - Using conditional matchers:
String horse = "horse";
String cow = "cow";
Ensure.that(horse, or(eq(horse), eq(cow)));
Ensure.that(cow, either(eq(horse), eq(cow)));
Ensure.that(horse, and(eq(horse), contains("ors")));
Ensure.that(cow, both(eq(cow), endsWith("ow")));
2 - Using negative matcher:
Ensure.that("horse", not(eq("cow")));
There are still a couple of matchers to talk about, one is the UsingEqualityMatchers class which is pretty much like JUnit Assert class, and the UsingExceptions class. Both also deserves your attention. Maybe someday I talk about them here. ![]()