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.

Technology Used

  • JBehave 3.6.8
  • Spring 3.1.1
  • JUnit 4.8.2
  • JBehave Eclipse plugin
  • JBehave Annotations
  • @AsParameterConverter
  • @When
  • @Given
  • @Then
  • Parametrised Scenarios
  • Parameter Injection
  • Outcomes Table
  • Tabular parameters

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

When I register a teen with age <age>

will be handled by the following method


@When("I register {a|an} $ageBand with age <age>")
public void registerMember(@Named("ageBand")AGE_BAND ageBand, @Named("age")int age) {

  • <age> is a parameter injection
  • {a|an} allows multiple stories to match the same annotation

the actual value of <age> comes from the table defined at the bottom

Examples:
|country|age|
|UK|19|
|FR|20|

JBehave has an Eclipse plugin that helps writing and validating story files.

References

JBehvae

Eclipse plugin

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: