<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Alexandre Martins &#187; Behaviour-Driven Development</title>
	<atom:link href="http://blog.m.artins.net/tag/behaviour-driven-development/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.m.artins.net</link>
	<description>On Agile Software Development</description>
	<lastBuildDate>Thu, 12 Aug 2010 20:09:21 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Hamcrest Out Of Test Code!</title>
		<link>http://blog.m.artins.net/hamcrest-out-of-test-code/</link>
		<comments>http://blog.m.artins.net/hamcrest-out-of-test-code/#comments</comments>
		<pubDate>Thu, 19 Feb 2009 12:38:30 +0000</pubDate>
		<dc:creator>Alexandre Martins</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Behaviour-Driven Development]]></category>
		<category><![CDATA[Coding]]></category>
		<category><![CDATA[Domain-Driven Design]]></category>
		<category><![CDATA[Functional Programming]]></category>
		<category><![CDATA[Tools]]></category>

		<guid isPermaLink="false">http://blog.m.artins.net/?p=168</guid>
		<description><![CDATA[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, [...]]]></description>
			<content:encoded><![CDATA[<p>It's been a while since I read <a href="http://joe.truemesh.com/blog/000705.html">some</a> <a href="http://jroller.com/ghettoJedi/entry/using_hamcrest_for_iterators">interesting</a> <a href="http://cromwellian.blogspot.com/2006/07/fun-with-generics-and-cglib-functional.html">posts</a> showing creative uses of <a href="http://code.google.com/p/hamcrest/">Hamcrest</a> library out of test code. Since then I've been proscrastinating to implement my own version, trying <a href="http://weblogs.java.net/blog/alexwinston/archive/2005/04/strongly_types_1.html">strongly typed java delegates</a>. </p>
<p>Thankfully this week I came across a nice API called <a href="http://code.google.com/p/hamcrest-collections/">hamcrest-collections</a>. It uses Hamcrest to implement features such as <strong><code>select</code></strong>, <strong><code>reject</code></strong>, <strong><code>map</code></strong>, <strong><code>reduce</code></strong> and <strong><code>zip</code></strong> familiar from languages like Ruby and Python. </p>
<h2>Selectors</h2>
<p>Selectors can be used to select or reject items that matches a given Matcher, from any iterable object. It reminds me the <a href="http://martinfowler.com/apsupp/spec.pdf">Specification Pattern</a> from <a href="http://domaindrivendesign.org/">Domain-Driven Design</a>, which is also used for querying objects that satisfies defined specifications.</p>
<pre style="border: solid gray 1px; width: 90%; padding: 10px;">
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<Person> list() {
    return Arrays.asList(john, nicole, ryan, nathan);
}</pre>
<p><br/><br />
The code below selects from the list of users defined above, the ones that are under twenty.</p>
<pre style="border: solid gray 1px; width: 90%; padding: 10px;">
@Test
public void should_select_only_people_under_twenty_years_old() {
    List<Person> users = Person.list();
    Iterable<Person> underTwentyList = select(users, underAge(20));
    assertThat(underTwentyList, hasItems(nicole, nathan));
    assertThat(underTwentyList, not(hasItems(john, ryan)));
}
</pre>
<p><br/><br />
The code below rejects all the users that are under twenty.</p>
<pre style="border: solid gray 1px; width: 90%; padding: 10px;">
@Test
public void should_reject_every_people_under_twenty_years_old() {
    List<Person> users = Person.list();
    Iterable<Person> aboveTwentyList = reject(users, underAge(20));
    assertThat(aboveTwentyList, hasItems(john, ryan));
    assertThat(aboveTwentyList, not(hasItems(nicole, nathan)));
}</pre>
<p><br/></p>
<h2>Map and Reduce</h2>
<p>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.</p>
<pre style="border: solid gray 1px; width: 90%; padding: 10px;">
@Test
public void should_double_each_number_in_the_list_then_sum_all_of_them() {
    List<Integer> numbers = Arrays.asList(1, 2, 3);
    MultiplyBy timesTwo = new MultiplyBy(2);

    Iterable<Integer> result = map(numbers, timesTwo);
    assertThat(result, hasItems(2, 4, 6));

    Integer sum = reduce(result, new Sum());
    assertThat(sum, equalTo(12));
}</pre>
<p><br/></p>
<pre style="border: solid gray 1px; width: 90%; padding: 10px;">
public class MultiplyBy implements Function<Integer, Integer> {
    private Integer factor;

    public MultiplyBy(Integer factor) {
        this.factor = factor;
    }

    public Integer apply(Integer number) {
        return (int)number * factor;
    }
}</pre>
<p><br/></p>
<pre style="border: solid gray 1px; width: 90%; padding: 10px;">
public class Sum implements Reducer<Integer> {
    public Integer apply(Integer first, Integer second) {
        return first + second;
    }
}</pre>
<p><br/></p>
<p>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! <img src='http://blog.m.artins.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.m.artins.net/hamcrest-out-of-test-code/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Acceptance Tests With JBehave, Selenium &amp; Page Objects</title>
		<link>http://blog.m.artins.net/acceptance-tests-with-jbehave-selenium-page-objects/</link>
		<comments>http://blog.m.artins.net/acceptance-tests-with-jbehave-selenium-page-objects/#comments</comments>
		<pubDate>Sat, 15 Nov 2008 00:30:54 +0000</pubDate>
		<dc:creator>Alexandre Martins</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Acceptance Tests]]></category>
		<category><![CDATA[Behaviour-Driven Development]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JBehave]]></category>
		<category><![CDATA[Page Objects]]></category>
		<category><![CDATA[Web Development]]></category>

		<guid isPermaLink="false">http://blog.m.artins.net/?p=117</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<p>Since <a href="http://jbehave.org/">JBehave 2.0</a> 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.</p>
<h3>What is JBehave?</h3>
<p>JBehave is a framework for <a href="http://behaviour-driven.org/">Behaviour-Driven Development</a>, 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.</p>
<h3>An Example</h3>
<p>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 <a href="http://www.ryangreenhall.com/articles/bdd-by-example.html">here</a>. The intention is to show how we are doing it on my project, integrating with <a href="http://selenium.openqa.org/">Selenium</a> and using the <a href="http://code.google.com/p/webdriver/wiki/PageObjects">Page Objects</a> pattern.</p>
<h4>New Feature</h4>
<p>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:</p>
<pre style="border: solid gray 1px; width: 80%; padding: 10px; margin:10px;">
As an user
I want to login into the website
So that I can view the exclusive contents
</pre>
<h4>Defining Scenarios</h4>
<pre style="border: solid gray 1px; width: 80%; padding: 10px; margin:10px;">
<strong>Scenario: Invalid Username</strong>
Given the user is on the login page
 When the user types username <em>wrong!</em>
  And the user types password <em>123456</em>
  And clicks the login button
 Then the page should display <em>Invalid Authentication</em> message

<strong>Scenario: Successful Login</strong>
Given the user is on the login page
 When the user types username <em>alexandre</em>
  And the user types password <em>123456</em>
  And clicks the login button
 Then the user should be redirected to home page
  And the page should display welcome message to <em>alexandre</em>
</pre>
<p>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.</p>
<pre name="code" class="java">
public class LoginScenarios extends Scenario {
	public LoginScenarios() {
		super(new LoginSteps());
	}
}
</pre>
<p><strong>Defining Steps (Integrating Selenium)</strong></p>
<p>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.</p>
<p>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. </p>
<p>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 <a href="http://pubbitch.org/blog/">Simon Stewart</a>, when he was in Sydney for the JAOO conference. He said that they implemented <a href="http://code.google.com/p/webdriver/">WebDriver</a> based on this pattern, and showed me some examples. Here is a definition, extracted from the WebDriver wikipage:</p>
<p><cite><br />
<blockquote>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.</p></blockquote>
<p></cite></p>
<pre name="code" class="java">
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();
	}
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.m.artins.net/acceptance-tests-with-jbehave-selenium-page-objects/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>First Sydney Coding Dojo</title>
		<link>http://blog.m.artins.net/first-sydney-coding-dojo/</link>
		<comments>http://blog.m.artins.net/first-sydney-coding-dojo/#comments</comments>
		<pubDate>Thu, 06 Nov 2008 13:33:57 +0000</pubDate>
		<dc:creator>Alexandre Martins</dc:creator>
				<category><![CDATA[Agile]]></category>
		<category><![CDATA[Coding]]></category>
		<category><![CDATA[Behaviour-Driven Development]]></category>
		<category><![CDATA[Dojo]]></category>
		<category><![CDATA[Pair Programming]]></category>

		<guid isPermaLink="false">http://blog.m.artins.net/?p=111</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<p>Last Wednesday, 5th of November, we run our first <a href="http://www.codingdojo.org/">Coding Dojo</a> session at Sydney office. We had a reasonable number of attendants, and the experience was fantastic, although we still have some points to improve.</p>
<h4>The Initiative</h4>
<p>The idea was originally from my friend and flat-mate <a href="http://www.markhneedham.com/blog/">Mark Needham</a>. Since we moved in to our new place, he came up with the idea of getting together every week to solve some <a href="http://codekata.pragprog.com/">CodeKatas</a> 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 <a href="http://www.thoughtworks.com/">ThoughtWorks</a> office.</p>
<h4>How did we run:</h4>
<p>There were six people attending, so we decided to split it into three pairs, each with their own solution, rotating every ten minutes.<br />
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 <a href="http://tinyurl.com/5v9qq2">Uncle Bob Martin's book</a>. We did it following the <a href="http://www.pragprog.com/titles/twa/thoughtworks-anthology">Object Calisthenics</a> rules, which are:</p>
<ul>
<li>Use only one level of indentation per method</li>
<li>Don't use the else keyword</li>
<li>Wrap all primitives and strings (strong types)</li>
<li>Use only one dot per line</li>
<li>Don't abbreviate</li>
<li>Keep all entities small</li>
<li>Don't use any classes with more than two instance variables</li>
<li>Use first-class collections</li>
<li>Don't use any getters/setters/properties</li>
</ul>
<h4>What was cool:</h4>
<p>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 <a href="http://ca.rroll.net/">Nick Carroll</a>.</p>
<h4>Future improvements:</h4>
<p>For the next session, I would like to experiment with another approach.<br />
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.</p>
<p>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.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.m.artins.net/first-sydney-coding-dojo/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JBehave Matchers</title>
		<link>http://blog.m.artins.net/jbehave-matchers/</link>
		<comments>http://blog.m.artins.net/jbehave-matchers/#comments</comments>
		<pubDate>Thu, 05 Jul 2007 03:29:32 +0000</pubDate>
		<dc:creator>Alexandre Martins</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[Behaviour-Driven Development]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JBehave]]></category>

		<guid isPermaLink="false">http://blog.m.artins.net/?p=11</guid>
		<description><![CDATA[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, [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://jbehave.org/">JBehave</a> and <a href="http://jmock.org/">JMock2</a> 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.</p>
<p>Matchers are handy objects, inspired by <a href="http://www.junit.org">JUnit</a> <a href="http://junit.sourceforge.net/javadoc/junit/framework/Assert.html">Assert</a> class, but much more elaborated. They can help us in loads of scenarios, without the need to write repeated code, such as <code>loops, ifs, elses</code>, turning out the code cleaner and much more intuitive. Currently there are six matcher subtypes: <strong>UsingArrayMatchers</strong>, <strong>UsingCollectionMatchers</strong>, <strong>UsingEqualityMatchers</strong>, <strong>UsingExceptions</strong>, <strong>UsingLogicalMatchers</strong> e <strong>UsingStringMatchers</strong>. For now, I'm just going to talk about four of them, which for me are the most innovative ones.</p>
<h3>UsingArrayMatchers e UsingCollectionMatchers</h3>
<p>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:</p>
<p>1 - Check if a Collection/Array contains a certain object:</p>
<pre name="code" class="java">
Integer[] array = new Integer[] {3};
Ensure.that(array, contains(3));
Ensure.that(array, not(contains(5)c));
</pre>
<p>2 - Check if a Collection/Array contains a certain set of objects:</p>
<pre name="code" class="java">
Integer[] array = new Integer[] {3, 4, 5};
Ensure.that(array, contains(3, 4));
Ensure.that(array, contains(3, 4, 5));
</pre>
<p>3 - Check if a Collection/Array contains only a certain set of objects, and nothing more:</p>
<pre name="code" class="java">
Integer[] array = new Integer[] {3, 4, 5};
Ensure.that(array, containsOnly(3, 4, 5));
Ensure.that(array, not(containsOnly(3, 4)));
</pre>
<p>4 - Check if a Collection/Array contains a certain set of objects, in a defined order:</p>
<pre name="code" class="java">
Integer[] array = new Integer[] {3, 4, 5};
Ensure.that(array, containsInOrder(3, 4, 5));
Ensure.that(array, not(containsInOrder(4, 5, 3)));
</pre>
<h3>UsingStringMatchers</h3>
<p>The methods in this class are self-explanatory, just check it out:</p>
<pre name="code" class="java">
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")));
</pre>
<h3>UsingLogicalMatchers</h3>
<p>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.</p>
<p>1 - Using conditional matchers:</p>
<pre name="code" class="java">
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")));
</pre>
<p>2 - Using negative matcher:</p>
<pre name="code" class="java">
Ensure.that("horse", not(eq("cow")));
</pre>
<p>There are still a couple of matchers to talk about, one is the <strong>UsingEqualityMatchers</strong> class which is pretty much like JUnit Assert class, and the <strong>UsingExceptions</strong> class. Both also deserves your attention. Maybe someday I talk about them here. <img src='http://blog.m.artins.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.m.artins.net/jbehave-matchers/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
