Home > Mobile >  How to assert that response String body is in JSON format?
How to assert that response String body is in JSON format?

Time:01-03

Hello guys how can I assert that response String body is in JSON format using RestAssured?

What I put instead of 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.

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

CodePudding user response:

You could simply have RestAssured do the JSON decoding for you. If it is not valid JSON this will fail with an exception:

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:

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:

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"));
  • Related