Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boolean parameters for SpecFlow steps

Tags:

c#

specflow

In SpecFlow, I want to check for the presence of a string in a step definition and at the moment I am doing clunky things like this contrived example:

[Given(@"Foo ( bar)?")]
public void GivenFoo(string bar)
{
    if (bar == " bar")
    {
        // do bar
    }
}

However, I'd like to do something like this:

[Given(@"Foo ( bar)?")]
public void GivenFoo(bool bar)
{
    if (bar)
    {
        // do bar
    }
}

But I can't find out how, so is this possible and if so how?

like image 937
Dean Barnes Avatar asked Apr 24 '13 14:04

Dean Barnes


1 Answers

You definitely can do that sort of thing, using a StepArgumentTransformation method. You still have to write the parser logic, but you can sequester it into a method who's only purpose is to perform that parsing.

Example feature file:

Feature: I win if I am Batman

Scenario: Happy
    Given I am the Batman
    Then I defeat the Joker

Scenario: Sad
    Given I am not the Batman
    Then I am defeated by the Joker

Specflow Bindings (C#):

[Binding]
public class IWinIfIAmBatmanFeature
{
    private bool iAmBatman;

    [StepArgumentTransformation(@"(am ?.*)")]
    public bool AmToBool(string value)
    {
        return value == "am";
    }

    [Given(@"I (.*) the Batman")]
    public void WhoAmI(bool amIBatman)
    {
        iAmBatman = amIBatman;
    }

    [StepArgumentTransformation(@"(defeat|am defeated by)")]
    public bool WinLoseToBool(string value)
    {
        return value == "defeat";
    }

    [Then(@"I (.*) the Joker")]
    public void SuccessCondition(bool value)
    {
        Assert.AreEqual(iAmBatman, value);
    }
}

The key factor is that the regex match in your Given clause is matched by the step argument transformation. So in I (.*) the Batman, if the capture matches the regex in the argument for the StepArgumentTransformation, as it does in the attribute for AmToBool then that is the transformation that gets used.

like image 80
Erik Avatar answered Sep 16 '22 18:09

Erik