Max Max - 1 month ago 13
C# Question

How can i generate missing values using table.CreateSet<>(myClass)() in SpecFlow?

I'm using SpecFlow for the very first time to write tests for my project and I ran into a small problem.

I have the next class:



public class FancyName
{
[DataMember]
public Guid Guid { get; set; }

[DataMember]
public string Name { get; set; }

[DataMember]
public List <Country> Countries { get; set; }
}


And I want to generate this class in my Tests using SpecFlow helpers.

Here is the part of Scenario:

[...]
When i add some names
| Name | Countries |
| UK | 1 |
| US | 2 |
[...]


I try to parse it in step definitions like this:

[When(@"I add some names")]
public void AddNames(Table table)
{
var names = table.CreateSet<FancyName>();
[...]
}


And I'm running into 2 problems:


  1. I do not pass the Guid because a want to generate it like
    Guid.NewGuid()
    so created object contain
    null

  2. I pass countries as sorting but i need to create
    List<Country>()
    .



I used to try iterate through Table and create
FancyName
objects manually but as I understand it is not SpecFlow way. I tried to look through documentation and wasn't lucky to find proper solution.

May be somebody know the really good way to solve this?
Thanks in advance.

Answer

Table.CreateSet<> can't perform magic. It can't know that its supposed to create a new Guid for your object, or that its supposed to create a list containing 2 countries. You'll have to create this object yourself I think.

The best way to solve this is to use a [StepArgumentTransformation]

something like this:

[StepArgumentTransformation]
public List<FancyName> TransformToFancyName(Table table)
{
    //create the list from the table contents
}

[When(@"I add some names")]
public void AddNames(List<FancyName> names)
{
    .. use your FancyNames here
}

specflow will call your StepArgumentTransformation for any Step which has an argument of List<FancyName> as the last parameter and a corresponding table in the feature

Comments