NBehave: Executing a Scenario

NBehave can initially very strange to developers … after all, the idea of “executing” a text file is simply foreign.  So here’s a brief run-down of how NBehave works. Let's suppose we have the following scenario file:

Given I have entered 1 into the calculator
And I have entered 2 into the calculator
When I add the numbers
Then the sum should be 3

NBehave processes this line-by-line.  So it picks up "Given I have entered 1 into the calculator" and will try to match this against a suitable method.  Classes that can provide such methods are attributed with [ActionSteps].  Let’s suppose the NBehave locates the following class:

[ActionSteps]
public class AddNumbers
{
    private Calculator _calculator;

    [BeforeScenario]
    public void SetUp_scenario()
    {
        _calculator = new Calculator();
    }

    [Given(@"I have entered $number into the calculator")]
    public void Enter_number(int number)
    {
        _calculator.Enter(number);
    }

    [When(@"I add the numbers")]
    public void Add()
    {
        _calculator.Add();
    }

    [Then(@"the sum should be $result")]
    public void Result(int result)
    {
        _calculator.Value().ShouldEqual(result);
    }
}

So NBehave matches our line of text to the following method, using the regular expression in the [Given] attribute:

[Given(@"I have entered $number into the calculator")]
public void Enter_number(int number)
{
    _calculator.Enter(number);
}

The value of 1 is captured by the regex from the text string, so NBehave calls "Enter_number(1)".  Well actually, since this is the very first step in the scenario NBehave first looks for a [BeforeScenario] attribute and so "SetUp_scenario()" will be executed before "Enter_number(1)".

The next line of the scenario "And I have entered 2 into the calculator" is matched to the same method ("And" is treated as equivalent to "Given" in this case) and so "Enter_number(2)" gets executed.

And so on and so on.  So overall, the scenario:

Given I have entered 1 into the calculator
And I have entered 2 into the calculator
When I add the numbers
Then the sum should be 3

will get translated into:

var calc = new AddNumbers();
calc.SetUp_scenario();
calc.Enter_number(1);
calc.Enter_number(2);
calc.Add();
calc.Result(3);

The final result, which I hope is now clear, is that the scenario file is really just a human-readable way of expressing code!

April 24 2010
blog comments powered by Disqus