JBehave example

Goal of this example

JBehave is a Java Behavior Driven Development (BDD) tool. BDD is a flavor of Test Driven Development (TDD), that requires tests to be written before the actual code. Writing a test against a non existing application may be challenging and that is where BDD can help. The idea is that user stories not only describe the requirements, but the tests too. This is achieved by parsing the user stories and using them as an input for regular (e.g.: JUnit) tests.

Structure of the example project

The src/main/java folder contains the actual classes that holds the business logic

The src/test/java folder contains the tests and story files

my.story defines the user stories that will be executed as a test

MyStories.java defines the mapping between the user story file(s) and the code that will be run

MySteps.java contains the actual steps of the test

How it works

The my.story file contains the user stories that are written using the Jbehave defined keywords (the sames as suggested by Scrum too). Meta and Narrative sections are just for information, the actual tests are executed by the given, when and then keywords.

“Given” defines the preconditions

“when” defines the actual test,

“then”compares the test results with the expected results.

MySteps.java is a stateful POJO, methods annotated with the @Given initialize the state that will be used by methods annotated with the @When, the result will be stored and later checked by methods with @Then annotation

As it can be seen tests are written in pure Java, but the actual order of calls and the parameter values are defined in the story file. For example the following sentence