简体   繁体   中英

Passing a value from a feature file into a JSON body in specflow c#

Scenario: Create System X Report
Given I have accessed System x's endpoint
When I make a Post request for the report 7890 with the title Report number 7890
Then I get a response
Then I verify the response

That is my scenario in my feature file, I want to pass "7890" & "Report number 7890" into this JSON body, which is on the post request within the Step Definition.

[When(@"I make a Post request for the report (.*) with the title Report number (.*)"), Scope(Tag = "post")]
    public void WhenIMakeAPostRequest(int report, String reporttitle)
    {
        RestRequest request = new RestRequest("upload_with_associations", Method.POST);
        request.AddHeader("Content-Type", "application/json");
        request.AddParameter("application/json", "report_urn\": \"{report}        " +
            "\"_links\": {\n            \"curies\": title\": \"**{reporttitle}**                 \"href\": \"https://report-service-apps.domain/docs/{rel}\",\n       " +
            "             ,\n        " +
            "    \"get-report-documents\": [\n                {\n                    \"href\": \"/api/report/<report_urn>/documents\"\n             " +
                   ]\n        },\n        \"report_urn\": \"**{report}**\",\n        \"report_source\": {\n          " +
             "          get-report-documents , ParameterType.RequestBody);
        IRestResponse response = client.Execute(request);
        statuscode = response.StatusCode;

    }

So I am passing in the values from the feature file into the step definition and then I am trying to replace the value in the json body as {report}, but I know this is wrong, so how can I pass the values into the json body?

[When(@"I make a Post request for the report (.*) with the title Report number (.*)"), Scope(Tag = "post")]
public void WhenIMakeAPostRequest(int report, String reporttitle)


request.AddParameter("application/json", "report_urn\": \"{report}

Try to use some json serializer, for example Newtonsoft.Json .

  1. Create a model (or several models) for the request body
  2. Create an instance of that model and apply incoming parameters to that model.
  3. Mark properties of that model by attribute `[JsonProperty] and use the name from your json
  4. Serialize it and use string instead of existing json string

The idea goes like this

  1. Take the parameter from feature
  2. Create a templete json with a identifier for dynamic usage
  3. Create aa script for read the items as map and replace the identifier by value from feature file Pli will post the code shortly

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM