18.4.12

JBehave yourself!

Here I wrote about techniques helping to build the right code: Specification by Example, ATDD and BDD. Today I want to present the first tool: JBehave.

The creator of JBehave is Dan North, who also introduced Behavior Driven Development (BDD). JBehave enables you to create executable specifications written in natural language, using the standard user story template Given, When, Then.

Given a stock of symbol STK1 and a threshold of 10.0
When the stock is traded at 5.0
Then the alert status should be OFF

This is the first part of your JBehave test suite, the Story, which is used for executing the actual test and for providing the test data. So, how does this work?
JBehave comes a long with some annotations, which define the steps of the story:

@Given("a stock of symbol $symbol and a threshold of $threshold")
public void aStock(String symbol, double threshold) {

@When("the stock is traded at $price")
public void theStockIsTradedAt(double price) {

@Then("the alert status should be $status")
public void theAlertShouldBe(String status) {

As you can see it is possible to define parts of the text as parameters by using the '$' sign. This way you can reuse your steps for various scenarios (one story consists of one or more scenarios). Within the method bodies you can do whatever you want; using Selenium to browse your website, doing Webservice calls or making assertions.
To execute your tests you need a class that inherits from "JUnitStories" as described here. So your tests are standard JUnit tests and have standard IDE support. Your tests can also be executed via Maven using the plugin.

Furthermore, JBehave comes along with out of the box reports for console, text, html and xml. As seen in the figure below, the output is quite informative.


What is the benefit?
The cool thing about JBehave and Specification by Example in general is, that there is no overhead in terms of additional work, especially for developers. The scenarios are (or should be) part of the defined specification, at least one. You can define more scenarios within your design session or when going through the user story with your requirements engineer. And your tests would have been written anyway ;)
Furthermore, you can use your usual test tools . JBehave is just  a thin layer above your tests, introducing some annotations.
Last but not least, the major benefit of JBehave and BDD compared to other approaches is, that you can use natural language. Making it very suitable for applications  or domains that are not specifiable using numbers. e.g. Given an existing customer with broadband and without pending orders.

No comments:

Post a Comment