Tuesday, August 16, 2011

JBehave - quick BDD example

After few last months of work on some projects with Spring MVC, Spring WebFlow, and JPA I had to do something else ;) - even for a while ;) - below you may find a results of my small experiments with Behavior Driven Development and JBehave :)

I started with Introducing BDD and What's in a Story? articles by Dan North, and Alex Soto blog entry about Spring Framework, JBehave and Selenium 2 integration.

Then I asked myself: "What I need for the BDD experiment? - The Story :) - I borrowed one from Dan's article What's in a Story?. Suppose that we have an Account, Card bound to this account, and ATM which will dispense some money. In order to get money when the bank is closed, as an account holder I want to withdraw cash from an ATM - this is the story :) - This story will have 3 possible scenarios in my example:


As you see, this story and the scenarios included are written in human language :) - no programming here, it can be written by anyone! OK, but where is the development here?! - Give me few minutes, and I'll explain that :)

Each Scenario consist of 3 steps: Given, When, Then. First one (Given) defines the context of the specific scenario (ex. "the card is disabled"), second (When) defines the event which occurred in this specific context (ex. "the account holder requests 20"), and third one (Then) defines the state of the context after the event processing (ex. "the ATM should retain the card").

Each scenario's step is bound to the Java code responsible for "implementing" it, in our example:


When you look at the @Given, @When, and @Then annotations you'll see that their values are matching the content of scenario steps written in human language - and this is the point where human language used by your Business Development Team meets the "Real Developers" ;)

Now what? - the rest is easy :) - Alex Soto proposed in his article (Spring Framework, JBehave and Selenium 2 integration) that we can use the Spring Framework driven Components for holding the Steps, this is very nice idea, and sufficient in my example (I would worry about it only in multi-threaded environment, because Component build by Spring is a Singleton by default, and that's usually not a good idea in such  environment).

Spring Framework configuration:


We perform the component scan here (which will register bean for our Steps holding class), and define only one bean related to JBehave, configuring its report builder.

Now we need a code which will allow us to run the Story processing as JUnit test:

When you run this test, all scenarios will be verified, and along with the JUnit test result, JBehave report will be produced:

Few links for the dessert: