Search code examples
c#cucumber.net-6.0specflow

How to pass json body through cucumber steps in C# and Cucumber


I need to send the below jsons through the cucumber feature file, So Like to know what would be the exact way I can define the json bodies under cucumber data table.
Even I tried to define as plain jsons in the table step definition is auto-generated with multiple parameters (parameter for each attribute)

Cucumber Scenario:

Scenario Outline: Send a few json bodies through the feature file
Given User generate request Url
When the User uses the "<jsonBody>"
Then User able to send
Examples:
|jsonBody|
|{"name":"John", "age":30, "car":null}|
|[{"name":"Mark", "age":28, "car":"Nissan"}, {"name":"brayn", "age":32, "car":"Mazda"}]|

If I tried the above steps, and step definition gots generated like below:

[When(@"the User uses the ""([^""]*)""name""([^""]*)""John""([^""]*)""age""([^""]*)""car""([^""]*)""")]
        public void WhenTheUserUsesTheNameJohnagecar(string p0, string p1, string p2, string p3, string p4)
        {
            throw new PendingStepException();
        }

Can Someone let me know the exact way to send the jsons and how the step definition method should be? when using .Net6.0 and SpecFlow Version:3.9.0.0


Solution

  • Instead of using double quotes We can use a single quote in json when it passes for the step definition

    Scenario Outline: Send a few json bodies through the feature file
    Given User generate request Url
    When the User uses the "<jsonBody>"
    Then User able to send
    Examples:
    |jsonBody|
    |{'name':'John', 'age':30, 'car':null}|
    |[{'name':'Mark', 'age':28, 'car':'Nissan'}, {'name':'brayn', 'age':32, 'car':'Mazda'}]|
    

    Then Step definition can create like below

    [When(@"the User uses the ""([^""]*)""")]  
    public void WhenTheUserUsesThe(string json)
    {
        // can apply logic to convert single quotes to double quotes
        Console.WriteLine(json);
    }