Search code examples
c#testingbddspecflowgherkin

SpecFlow - C# - var abc =table.CreateInstance<>() null


I have this scenario. Basically I want to log in with certain roles and then enumerate through the table of values at a point in my test to see if they are all viewable.

Scenario Outline: View something with user.
    Given I navigate to the application with "<Role>"
    When I view something for "<SubRole>"
    Then all things should be viewable for "<SubRole>"
        | Sequence | Things |
        | 1        | thing1 |
        | 2        | thing2 |
        | 3        | thing3 |
        | 4        | thing4 |

    @Dev
    Examples:
        | Role       | SubRole|
        | System role| user1  |
 [Then(@"all things should be viewable for ""(.*)""")]
        public void ThenAllThingsShouldBeViewableFor(string subRole, Table table)
        {
         
             var things = table.CreateInstance<AllThings>();

   foreach (var stuff in things)
           {
             //code to check if all things in table are viewable
           }
public class AllThings
{
    public string Sequence { get; set; }
    public string Things{ get; set; }

}

However var things = null for both Sequence and Things and i cant figure out why? The table populates fine but I cant assign it to the variable 'things' as it just returns null

Then when it comes to the foreach loop i get a 'System.NullReferenceException: 'Object reference not set to an instance of an object.''


Solution

  • Also as you are expecting an Enumerable, you have to use CreateSet and not CreateInstance.

    So it should look like this:

    [Then(@"all things should be viewable for ""(.*)""")]
    public void ThenAllThingsShouldBeViewableFor(string subRole, Table table)
    {
        var things = table.CreateSet<AllThings>();
        foreach (var stuff in things)
        {
              //code to check if all things in table are viewable
        }
    }
    

    See docs for this: https://docs.specflow.org/projects/specflow/en/latest/Bindings/Step-Definitions.html#table-or-multi-line-text-arguments