简体   繁体   English

如何断言响应字符串主体是 JSON 格式?

[英]How to assert that response String body is in JSON format?

Hello guys how can I assert that response String body is in JSON format using RestAssured?大家好,我如何使用 RestAssured 断言响应字符串正文为 JSON 格式?

What I put instead of XXX我用什么代替 XXX

  Response response =
            RestAssured.given()
                    .with()
                    .param("username", TEST_USER_EMAIL)
                    .get(API_PREFIX_URL + PUBLIC_ROUTE + PUBLIC_USER_CONTENT);
    
  response.then().assertThat().body(XXX)

I want assert that if this String for example is in valid json format.我想断言如果这个字符串例如是有效的 json 格式。

'{"name":"John", "age":30, "car":null}'

You could simply have RestAssured do the JSON decoding for you.您可以简单地让 RestAssured 为您执行 JSON 解码。 If it is not valid JSON this will fail with an exception:如果它无效 JSON 这将失败并出现异常:

final Response response = RestAssured.given()
        .with()
        .param("username", TEST_USER_EMAIL)
        .get(API_PREFIX_URL + PUBLIC_ROUTE + PUBLIC_USER_CONTENT);
    
response.then().assertThat()
        .statusCode(HttpStatus.OK.value())
        .body("name", equalTo("John")) // Hamcrest matchers
        .body("age", equalTo(30))
        .body("car", nullValue());

Or fully map to a class which describes your expected format:或者完全 map 到 class 描述您的预期格式:

static class Person {
  public String name;
  public int age;
  public String car;
}

final Response response = RestAssured.given()
        .with()
        .param("username", TEST_USER_EMAIL)
        .get(API_PREFIX_URL + PUBLIC_ROUTE + PUBLIC_USER_CONTENT);
    
final Person person = response.then().assertThat()
        .statusCode(HttpStatus.OK.value())
        .extract()
        .as(Person.class);
assertEquals("John", person.name);
assertEquals(30, person.age);
assertEquals(null, person.car);

And if you want to be really explicit, you can extract the response as string and then parse it with Jackson's ObjectMapper yourself:而且,如果您想非常明确,可以将响应提取为字符串,然后自己使用 Jackson 的 ObjectMapper 对其进行解析:

final ObjectMapper mapper = new ObjectMapper();
final Response response = RestAssured.given()
        .with()
        .param("username", TEST_USER_EMAIL)
        .get(API_PREFIX_URL + PUBLIC_ROUTE + PUBLIC_USER_CONTENT);
    
final String jsonString = response.then().assertThat()
        .statusCode(HttpStatus.OK.value())
        .extract()
        .asString();
final Map<String, Object> jsonMap = mapper.readValue(jsonString, new TypeReference<>(){});
assertEquals("John", jsonMap.get("name"));
assertEquals(30, jsonMap.get("age"));
assertEquals(null, jsonMap.get("car"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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