Search code examples
c#bddspecflow

How to get the specflow scenarios in c# objects


I want to read each feature file and create objects for each scenario. After reading the .feature file. I should get objects like below:

Input

@mytag  
Scenario: Add two numbers  
    Given I have entered 50 into the calculator  
    And I have entered 70 into the calculator  
    When I press add  
    Then the result should be 120 on the screen

Expected Output

Scenarios - Gives all the scenarios in feature file.
Scenario.Steps - Gives all the Given when then of that scenarios.
Scenario.Examples - Gives all the examples.
Scenarios.Tags - All the tags

Code

var lines = File.ReadAllText(@"P:\Test.feature");
var scenarios = lines.Split(new string[] { "Scenario: "}, StringSplitOptions.RemoveEmptyEntries);
var scenarioList = new List<Scenario>();
for (int i = 1; i < scenarios.Length; i++)
{
    var ind = scenarios[i].IndexOf("\n");

    var scenario = new Scenario();
    scenario.Name = scenarios[i].Substring(0, ind);
    var toInd=scenarios[i].IndexOf("@");
    if(toInd>1)
        scenario.Steps = scenarios[i].Substring(ind,toInd);
    else
        scenario.Steps = scenarios[i].Substring(ind);
    scenarioList.Add(scenario);
}

Solution

  • Gherkin Parser should do what you're expecting. You can get it at Nuget gallery