JBehave 2, naming tests and developing libraries with BDD

Peter Bell and I had a great conversation over Skype yesterday, which he’s kindly blogged. We covered test names, and also talked about how to develop libraries using BDD. Again, this is how I do things; it’s not necessarily the only way.

Peter’s mentioned JBehave 2, so the secret’s out now – yes, it’s in progress. It’s not publically available because it’s just a spike at the moment. We’re starting afresh, learning some of the lessons that made JBehave 1.0 hard to use, taking advantage of JUnit 4’s features, and drawing heavily on the success of RSpec.

Our goals for JBehave 2 include:

  • no internal support for mocking – should be able to use any of the libraries
  • extends JUnit – right-click and run both behaviours and scenarios
  • uses Hamcrest’s matchers
  • uses plain-text scenarios à la RSpec

Here’s a sneak preview of the spike so far.

We have a scenario file, i_can_toggle_a_cell:

Given a 5 by 5 game
When I toggle the cell at (2, 3)
Then the grid should look like
.....
.....
.....
..X..
.....
When I toggle the cell at (2, 4)
Then the grid should look like
.....
.....
.....
..X..
..X..
When I toggle the cell at (2, 3)
Then the grid should look like
.....
.....
.....
.....
..X..

We have a small class in the same package to run this, called ICanToggleACell.java (the Scenario class is a JUnit test):

package com.lunivore.gameoflife;

import org.jbehave.scenario.Scenario;

import com.lunivore.gameoflife.steps.GridSteps;

public class ICanToggleACell extends Scenario {

 

@SuppressWarnings("unchecked")
public ICanToggleACell() {
super(new GridSteps());
}
}

And we have steps defined thus:


package com.lunivore.gameoflife.steps;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.jbehave.Ensure.ensureThat;

import org.jbehave.scenario.annotations.Given;
import org.jbehave.scenario.annotations.Then;
import org.jbehave.scenario.annotations.When;
import org.jbehave.scenario.steps.Steps;

import com.lunivore.gameoflife.domain.Game;
import com.lunivore.gameoflife.view.string.StringRenderer;

public class GridSteps extends Steps {

  private Game game;
  private StringRenderer renderer;

  @Given("a $width by $height game")
  public void theGameIsRunning(int width, int height) {
    game = new Game(width, height);
    renderer = new StringRenderer();
    game.setObserver(renderer);
  }

  @When("I toggle the cell at ($column, $row)")
  public void iToggleTheCellAt(int column, int row) {
    game.toggleCellAt(column, row);
  }

  @Then("the grid should look like $grid")
  public void theGridShouldLookLike(String grid) {
    ensureThat(renderer.asString(), equalTo(grid));
  }

 

}

I’m excited that this actually works. The next step is to get appropriate error messages when the scenario fails! We’re working hard to get this out to you as soon as we can; watch this space.

This entry was posted in bdd, jbehave. Bookmark the permalink.