SpecFlow - How to setup test data on a entity with a custom type

Viewed 302

Using SpecFlow in a C# -Entity Framework application, I'm trying to set up test data for an Entity of below structure.

public partial class TYPE1
{
    public int Prop1 { get; set; }
    public virtual ICollection<TYPE2> Prop2 { get; set; }
}

public partial class TYPE2
{
    public int Prop3 { get; set; }
}

Test data :

Given I have a Type1 record with following data
| Prop1 | Prop2 |
| 123   | 0     |


[Given(@"I have a Type1 record with following data")]
public void GivenIHaveAType1RecordWithFollowingData(Table table)
{
    foreach (var row in table.Rows)
    {
        var record =
            this.PopulateModelFromTableRow<TYPE1>(row);
        this.test.DbContext.TYPE1.Add(record);
    }
}

I'm trying to figure out a way to assign Prop2 a list of Type 2 values. How can i do that?

1 Answers

You will need to create the entity and populate the collection in two separate steps:

Given I have a Type1 record with following data
    | Prop1 |
    | 123   |
And the Type1 record I just created as the following Prop2:
    | Prop2 |
    | 0     |
    | 4     |

The first step will create a new Type1 object and save it with an empty collection of Prop2. The next step should fetch the Type1 object you just created and add items to the collection using the data table.

Gherkin was never designed to build complex objects containing collections in a single step. There are ways around it, but they often result in tests that are harder to read and maintain. The best practice is to populate collection properties of an entity in a specialized step.

Related