Rest-assured. Is it possible to extract value from request json?

前端 未结 5 901
死守一世寂寞
死守一世寂寞 2020-12-24 00:36

I\'m getting response this way:

Response response = expect().statusCode(200).given().body(requestBody).contentType(\"application/json\")
.when().post(\"/admi         


        
相关标签:
5条回答
  • 2020-12-24 01:19

    To serialize the response into a class, define the target class

    public class Result {
        public Long user_id;
    }
    

    And map response to it:

    Response response = given().body(requestBody).when().post("/admin");
    Result result = response.as(Result.class);
    

    You must have Jackson or Gson in the classpath as the documentation states: http://rest-assured.googlecode.com/svn/tags/2.3.1/apidocs/com/jayway/restassured/response/ResponseBodyExtractionOptions.html#as(java.lang.Class)

    0 讨论(0)
  • 2020-12-24 01:25

    There are several ways. I personally use the following ones:

    extracting single value:

    String user_Id =
    given().
    when().
    then().
    extract().
            path("user_id");
    

    work with the entire response when you need more than one:

    Response response =
    given().
    when().
    then().
    extract().
            response();
    
    String userId = response.path("user_id");
    

    extract one using the JsonPath to get the right type:

    long userId =
    given().
    when().
    then().
    extract().
            jsonPath().getLong("user_id");
    

    Last one is really useful when you want to match against the value and the type i.e.

    assertThat(
        when().
        then().
        extract().
                jsonPath().getLong("user_id"), equalTo(USER_ID)
    );
    

    The rest-assured documentation is quite descriptive and full. There are many ways to achieve what you are asking: https://github.com/jayway/rest-assured/wiki/Usage

    0 讨论(0)
  • 2020-12-24 01:30

    You can also do like this if you're only interested in extracting the "user_id":

    String userId = 
    given().
            contentType("application/json").
            body(requestBody).
    when().
            post("/admin").
    then().
            statusCode(200).
    extract().
            path("user_id");
    

    In its simplest form it looks like this:

    String userId = get("/person").path("person.userId");
    
    0 讨论(0)
  • 2020-12-24 01:31

    I found the answer :)

    Use JsonPath or XmlPath (in case you have XML) to get data from the response body.

    In my case:

    JsonPath jsonPath = new JsonPath(responseBody);
    int user_id = jsonPath.getInt("user_id");
    
    0 讨论(0)
  • 2020-12-24 01:32
    JsonPath jsonPathEvaluator = response.jsonPath();
    return jsonPathEvaluator.get("user_id").toString();
    
    0 讨论(0)
提交回复
热议问题