Home > Software engineering >  Specflow allowing nullable Table parameter
Specflow allowing nullable Table parameter

Time:09-23

Here is an example step from a scenario:

Given ...
...
When create ride ticket
    | hour | passangers | ... |
And create ride ticket rideNumber 3
...
Then ride is successful

(I kept the relevant part, its unnecessary to understand what the scenario is about)

With this step implementation:

[When(@"create\s*ride(?: rideNumber (. ))?")]
public void WhenCreateRide(int? rideNumber , Table rideDetails)
{
    ...
}

I added this new Table parameter to the step definition. The previous logic took the details from another step definiton. I am trying to allow both old logic and a new logic - passing a Table directly to this step definition.

If I remove the rideNumber 2 part of the step (like in the first When statement), the method above will treat the rideNumber parameter as null (since I marked it as nullable). But if I don't pass a table at all to the scenario - it will throw a binding exception.

I have many (over 100) scenarios using this old logic (therefor they don't have a table passed to them), so adding a Table to all of them seems like the last thing I want to do.

Any idea why is it not treating the Table as null if I dont pass it? Any idea how to overcome the problem?

CodePudding user response:

These should be separate step definitions, otherwise you get into this precise situation. You'll spend far more time trying to get this to work than creating two separate step definitions. You might have to rename one of the step definition methods from the default name suggested by SpecFlow when generating step defs.

[When(@"create ride ticket rideNumber (. )")]
public void WhenCreateRideWithNumber(int rideNumber)
{
    ...
}

[When(@"create ride ticket")]
public void WhenCreateRideTicket(Table rideDetails)
{
    ...
}

If these two step definitions have common logic, create a private method containing the common logic, and then call this private method from both step definitions:

[When(@"create ride ticket rideNumber (. )")]
public void WhenCreateRideWithNumber(int rideNumber)
{
    ...
    CreateRideTicket(...);
    ...
}

[When(@"create ride ticket")]
public void WhenCreateRideTicket(Table rideDetails)
{
    ...
    CreateRideTicket(...);
    ...
}

private void CreateRideTicket(...)
{
    // common logic
}
  • Related