Backgrounds - adamralph/xbehave.net GitHub Wiki

xBehave.net allows the addition of background steps, equivalent to Cucumber Background.

E.g.

public class CalculatorFeature
{
    private Calculator calculator;

    [Background]
    public void Background() // this method can have any name
    {
        "Given a calculator"
            .x(() => this.calculator = new Calculator());
    }

    [Scenario]
    public void Addition(int x, int y, int answer)
    {
        "Given the number 1"
            .x(() => x = 1);

        "And the number 2"
            .x(() => y = 2);

        "When I add the numbers together"
            .x(() => answer = calculator.Add(x, y));

        "Then the answer is 3"
            .x(() => Assert.Equal(3, answer));
    }

    [Scenario]
    public void Multiplication(int x, int y, int answer)
    {
        "Given the number 2"
            .x(() => x = 2);

        "And the number 3"
            .x(() => y = 3);

        "When I multiply the numbers together"
            .x(() => answer = calculator.Multiply(x, y));

        "Then the answer is 6"
            .x(() => Assert.Equal(6, answer));
    }
}

The background method is executed exactly once before each scenario.

Any disposable objects or teardown delegates registered in a background method are executed after the execution of each scenario.

For another example see the blog post "New Background Attribute in xBehave.net 0.12.0".

When the background steps need to span multiple classes, they can be moved to a common base class. E.g.:

public abstract class CoolFeature
{
    [Background]
    public void Background()
    {
        "Given..."
            .x(() => ...);
        "And..."
            .x(() => ...);
        ...
    }
}
public class ReallyCoolFeature : CoolFeature
{
    [Scenario]
    public void BeingReallyCool()
    {
        ...
    }
}
public class UltraCoolFeature : CoolFeature
{
    [Scenario]
    public void BeingUltraCool()
    {
        ...
    }
}