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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With