简体   繁体   中英

How to verify the data type of Json response field in rest assured

How can we verify the Json data type of mentioned fields such as "price", "ck", "name", "enabled" and "tags" in rest assured test.

    {
      "odd": {
        "price": 200,
        "ck": 12.2,
        "name": "test this",
        "enabled": true,
        "tags": null
      }
    }

Is there any way or any assertion library which provide data type verification as mentioned in rest assured test example where instead of asserting the actual value of given key we can verify only the data type as mentioned in below example.

ValidatableResponse response =
            
given().
    spec(requestSpec).
    headers("authkey", "abcdxxxxxxxxxyz").
    pathParam("uid", oddUid).
when().
    get("/orders" + "/{uid}").
then().
    assertThat().
    statusCode(200).
    body(
           "odd.price",  isNumber(),
           "odd.name", isString(),
           "enabled", isboolean()
           "tags", isNull()
         );

If we want to validate our response in .body() method, then we can use Rest-Assured build-in matchers using Matchers class:

import static org.hamcrest.Matchers.isA;
import static org.hamcrest.Matchers.nullValue;

...

given().
    spec(requestSpec).
    headers("authkey", "abcdxxxxxxxxxyz").
    pathParam("uid", oddUid).
when().
    get("/orders" + "/{uid}").
then().
    body("odd.price", isA(Integer.class)).
    body("odd.name",  isA(String.class)).
    body("enabled",   isA(Boolean.class)).
    body("tags",      nullValue()).

OR we can use some assertion library, eg AssertJ:

import static org.assertj.core.api.Assertions.assertThat;

...

JsonPath response = given().
    spec(requestSpec).
    headers("authkey", "abcdxxxxxxxxxyz").
    pathParam("uid", oddUid).
when().
    get("/orders" + "/{uid}").
then().
extract().jsonPath();

assertThat(jsonPath.get("odd.price") instanceof Integer).isTrue();

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