<?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>Jayway Team Blog &#187; unit test</title>
	<atom:link href="http://blog.jayway.com/tag/unit-test/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.jayway.com</link>
	<description>Sharing Experience</description>
	<lastBuildDate>Sat, 11 Feb 2012 10:33:02 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Behaviour Driven Development</title>
		<link>http://blog.jayway.com/2008/02/01/behaviour-driven-development/</link>
		<comments>http://blog.jayway.com/2008/02/01/behaviour-driven-development/#comments</comments>
		<pubDate>Fri, 01 Feb 2008 11:38:33 +0000</pubDate>
		<dc:creator>Andreas Ronge</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[bdd]]></category>
		<category><![CDATA[jayview]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tdd]]></category>
		<category><![CDATA[unit test]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=3392</guid>
		<description><![CDATA[Test Driven Development is a well established programming technique for creating high quality software. It is less known, however, that TDD is not only a programming technique but also a design methodology. The main goal of Behaviour Driven Development, a TDD based methodology, is to identify behaviours in both the analysis and the design phases. [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Test Driven Development is a well established programming technique for creating high quality software. It is less known, however, that TDD is not only a programming technique but also a design methodology.<br />
</strong></p>
<p>The main goal of Behaviour Driven Development, a TDD based methodology, is to identify behaviours in both the analysis and the design phases.<br />
In BDD [1] the test code looks more like a specification of behaviours than a test of the production code.</p>
<h2>Test Driven Development </h2>
<p>TDD can be summarized in one rule:<br />
“Writing code is only allowed if you have a failing unit test”. </p>
<p>The TDD development cycle:<br />
   1. Write a unit test<br />
   2. Run all tests and make sure the new one fails<br />
   3. Implement the simplest possible solution in order to make the test pass<br />
   4. Refactor the code. All tests must pass after the refactoring has been done.<br />
   5. Repeat - write a new unit test </p>
<h3>Problems:</h3>
<ul>
<li>	Unit	tests	suggest	a	strong	relationship	between	test	class	and	implementation<br />
class. Each class or method usually has a corresponding test class or test meth-<br />
od. This causes a high coupling between the class under test and the test case.<br />
It also means that we focus too early on the implementation details, instead of<br />
doing the design first.
<li>	Unclear	definition	of	granularity	of	units.	A	common	mistake	is	to	mix	up	unit test with integration tests - which may require complex setup of several com-<br />
ponents (like a database). Having a high coupling between test code and the<br />
implementation is a serious problem when later on refactoring is needed. In-<br />
stead one should use mock objects to explore interactions between objects.
<li>	Limitations	on	mock	objects	may	have	too	big	an	impact	on	the	design.	We<br />
often have to stop using the private, static and final keywords. This problem was<br />
discussed in the previous issue of JayView - Mocking Static Methods.
</ul>
<h2>The Marriage of Component<br />
Specification with Unit Test </h2>
<p>BDD has a similar development cycle, but instead of writing tests before coding you<br />
write specifications before coding.<br />
A specification consists of a description of behaviours which are expressed within a<br />
context. Behaviours become self-verifying by writing (coding) expectations in the<br />
form of examples. The specification is written in an executable form so that we can<br />
generate a readable specification and verify that its expectations are valid. </p>
<h3>Example </h3>
<p>For example let’s write a specification for a stack. We start by identifing its contexts,<br />
which are: “empty”, “neither empty nor full”, “full”. Example of behaviours for the<br />
empty context are: “should be empty”, “should not be empty after a push”. For each<br />
of those one continue to write expectations. Like TDD you specify a small set of<br />
behaviours at a time then implement it - short iterations.<br />
Let’s show how this can be done using standard JUnit since it is a well known<br />
tool. JUnit is not a good tool for doing BDD since it was only designed for doing<br />
testing. A more suitable tool is for example JDave [4] or RSpec [2] which let you<br />
create much more readable specification. (The analysis part of RSpec is shown in<br />
the next section). </p>
<pre>// The enclosed annotation makes JUnit run all inner classes as tests
@RunWith(org.junit.runners.Enclosed.class)
public class StackTest {
    public static class EmptyStack {
        private Stack stack;
        @Before
        public void before() {
            stack = new Stack();
        }
        @Test
        public void shouldBeEmpty() {
            assertTrue(stack.isEmpty());
        }
        @Test
        public void shouldNotBeEmptyAfterAPush() {
            stack.push(“Some value”);
            assertFalse(stack.isEmpty());
        }
        // ...
    }
    public static class NeitherEmptyNorFullStack {
        private Stack stack;
        @Before
        public void before() {
            stack = new Stack();
            stack.push(“x”);
        }
        @Test
        public void shouldAddToTheTopWhenSentPush() {
            stack.push(“y”);
            assertEquals(“y”, stack.peek());
        }
        // ...
    }
}
</pre>
<p>By replacing the word “test” with “should” and organizing tests around behaviours it<br />
becomes clear that we are using BDD to drive the design.<br />
This format also allows us to generate an even more readable specification by using<br />
for example the junitreport ant task with a custom style sheet that extracts the bold<br />
words. A proper BDD tool would have this ability built in. I believe this specification<br />
is much better than the (class) javadoc that are often missing or incorrect.<br />
As shown above we keep specification and test together in an executable unit. This<br />
approach can also be used at a system level. </p>
<h2>The Marriage of Application<br />
Requirements with Acceptance Tests </h2>
<p>Requirements and acceptance tests are captured using a template containing a story<br />
and one or more scenarios.<br />
<strong>As a</strong> Role, <strong>I want</strong> Feature, <strong>So that</strong> Benefit<br />
Scenario1: <strong>Given</strong> ... <strong>When</strong> ... <strong>Then</strong><br />
Scenario2 ...<br />
A story’s behaviour is its acceptance criteria - the scenarios. By using the template<br />
above we can collaborate on stories with customers. This is nothing new, it is just<br />
one way of doing analysis.<br />
What is new is that in BDD the specification is written down in an executable<br />
unit in order to have self-verifying tests. The Ruby RSpec tool has a slightly different<br />
approach. It can treat specification written in plain english as an executable unit. </p>
<h3>An example of a story:</h3>
<p>Story: transfer to cash account<br />
<strong>As a</strong> savings account holder<br />
<strong>I want</strong> to transfer money from my savings account<br />
<strong>So that</strong> I can get cash easily from an ATM<br />
Scenario: savings account is in credit<br />
<strong>Given</strong> my savings account balance is 100<br />
And my cash account balance is 10<br />
<strong>When</strong> I transfer 20 from my savings account to my cash account<br />
<strong>Then</strong> my savings account balance should be 80<br />
And my cash account balance should be 20<br />
Scenario: savings account is overdrawn<br />
<strong>Given</strong> my savings account balance is -20<br />
And my cash account balance is 10<br />
<strong>When</strong> I transfer 20 from my savings account to my cash account<br />
<strong>Then</strong> my savings account balance should be -20<br />
And my cash account balance should be 10</p>
<p>To perform verification on this specification we create an interpreter where we de-<br />
fine reusable test steps. </p>
<pre>class AccountSteps < Spec::Story::StepGroup
  steps do |define|
    define.given("my $account account balance is $balance") do |account,
balance|
      @accounts ||= {} # creates a new hash if @accounts is nil
      @accounts[account] = Account.new(balance.to_f)
    end
    define.then("my $account account balance should be $amount") do |account,
amount|
      @accounts[account].balance.should == amount.to_f
    end
    define.when("I transfer $amount from my $from account to my $to account")
do |amount, from, to|
       @accounts[from].transfere_to(@accounts[to], amount.to_f)
    end
  end
end
</pre>
<p>To run it we need to tell which steps are using what story:</p>
<pre>runner = Spec::Story::Runner::PlainTextStoryRunner.new(filename-of-the-story)
runner.steps << AccountSteps.new
runner.run </pre>
<p>RSpec matches each line in the story with the defined test steps. The code inside the<br />
define block will be executed if a match is found.<br />
For example, when the story runner reads the line “Given my savings account bal-<br />
ance is 100” it will execute </p>
<pre>@accounts['savings'] = Account.new("100".to_f).
</pre>
<p>That means a new account object is created and stored in the accounts hash. </p>
<p>Still stuck with Java ? Psst, you can use JRuby [5] to test and mock Java<br />
objects. For example, try the JtestR [6] tool which also integrates nicely<br />
with ant, maven and Buildr [3]. </p>
<h2>Conclusions</h2>
<p>There is not a big difference between TDD and BDD if TDD is used  correctly. TDD<br />
often causes brittle test code - a small change in the  production code may cause a<br />
major change in the test code. BDD gives the possibility of structuring tests to make<br />
them “refactoring friendly”. This is accomplished by organizing tests in small focused<br />
examples of  behaviours.<br />
People are not always aware that TDD is able to drive the design. By not  thinking<br />
in terms of tests but instead describing the what and why of  behaviours, it becomes<br />
clear that BDD is a methodology for analysis and design. </p>
<h2>References</h2>
<p>[1] BDD - <a href="http://behaviour-driven.org/">http://behaviour-driven.org/</a><br />
[2] RSpec - <a href="http://rspec.rubyforge.org/">http://rspec.rubyforge.org/</a><br />
[3] Buildr - <a href="http://buildr.rubyforge.org/">http://buildr.rubyforge.org/</a><br />
[4] JDave - <a href="http://www.jdave.org/">http://www.jdave.org/</a><br />
[5] JRuby - <a href="http://jruby.codehaus.org/">http://jruby.codehaus.org/</a><br />
[6] JtestR - <a href="http://jtestr.codehaus.org">http://jtestr.codehaus.org</a></p>
<p><em>Originally published in <a href="http://jayway.se/jayview">JayView</a>.</em></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2008/02/01/behaviour-driven-development/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

