Passing parameters between tests with RestSharp



  • As I'm getting more familiar with the RestSharp client library for my API testing I'm confortable with using it for single API response checks e.g. checking a status code is correct, or that the response body is as expected.

    However, I'm now looking at more complex tests, namely passing parameters from one API to be used in another. Is anyone aware of how this can be done using RestSharp and, if so, an example would be very useful.

    I've provided an example below of something similar I've done in RestAssured(Java) but I'm now looking to do this using RestSharp and C#

    @Test
    public void test_ScenarioRetrieveFirstCircuitFor2017SeasonAndGetCountry_ShouldBeAustralia() {
    
        // First, retrieve the circuit ID for the first circuit of the 2017 season
        String circuitId = given().
        when().
            get("http://ergast.com/api/f1/2017/circuits.json").
        then().
            extract().
            path("MRData.CircuitTable.Circuits.circuitId[0]");
    
        // Then, retrieve the information known for that circuit and verify it is located in Australia
        given().
            pathParam("circuitId",circuitId).
        when().
            get("http://ergast.com/api/f1/circuits/{circuitId}.json").
        then().
            assertThat().
            body("MRData.CircuitTable.Circuits.Location[0].country",equalTo("Australia"));
    }
    


  • All you need to do is store part of the response in a variable (i.e. the data you want to use in the next request) and inject it again.

    1. Execute the request and catch the IRestResponse
    2. Extract the value using JsonPath from the Content property of the response object
    3. If the next request is a POST, load JSON as string and replace a mock value with the value extracted in the previous step. If the next request is a GET, replace a mock value in the URL of the API with the extracted value.
    4. Send your second request with the replaced data.

    Example (abbreviated to key actions only)

    var client = new RestClient("base url here");
    var response = client.Execute(request);
    
    // get a value
    var id = JToken.Parse(response.Content).SelectToken("data.id").ToObject<int>();
    
    // for a query parameter in your next call, you might do:
    var request = new RestRequest();
    request.AddQueryParameter("id", id); // re-use value
    
    // for a POST Json body request, you might do:
    var body = @"
    {
        "search": {
            "id": {id},
            "name": "test"
        }
    }";
    body = body.Replace("{id}", id);
    
    // add the body to the request
    request.AddParameter("application/json", body, ParameterType.RequestBody);
    


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2