Parsing and assertion json response body using REST-Assured

Dahun Yoo·2020년 12월 19일
0
post-thumbnail

Request를 하면 Respones가 오는데, 이 Response가 json format일 경우 어떻게 parsing하고, assert를 해야할까요?

Parse response

예를 들어, response를 string으로 뽑아내고 싶다면?

String response = given().log().all()
                        .queryParam("key", "value")
                        .header("Content-Type", "application/json")
                        .body(Payload.AddPlace())
                .when().post("/maps/api/place/add/json")
                .then().log().all()
                        .statusCode(200)
                        .body("scope", Matchers.equalTo("APP"))
                        .header("Server", Matchers.equalTo("Apache/2.4.18 (Ubuntu)"))
                        .extract().response().asString();

결국 마지막에 extract().response().asString() 을 이용해 모든 response를 String으로 추출해냅니다.

JsonPath js = new JsonPath(response);
String place_id = js.getString("place_id");

JsonPath를 이용해서 특정 attribute를 다시 뽑아낼 수도 있습니다.
혹은 extract().response().jsonPath() 로 바로 JsonPath로 뽑아낼 수 있습니다.

Assert response

REST-Assured에서는 assertThat() 이라는 메소드를 이용해서, 기댓값과 결과값이 일치하는지를 지원해줍니다.

status code

status code는 statusCode() 메소드를 통해 값과 일치하는지 확인할 수 있습니다.

body

body값에서는 Matchers.equalTo() 를 통해 기대값과 body의 value값을 확인할 수 있습니다.
Matchers를 사용하기 위해서는 일단 static import가 필요합니다.
import static org.hamcrest.Matchers.*;

then().assertThat().statusCode(200).body("scope", Matchers.equalTo("APP"));

위의 경우는, statusCode가 200이 맞는지,
body값의 scope attribute의 value값은 "APP"이 맞는지 확인합니다.

이렇게 assertion기능을 내장하고 있지만, 태그 기능과 테스트 실행 순서, 외부 플러그인을 통한 report 등을 고려한다면, jUnit 혹은 TestNG와 같이 사용하는 것이 좋습니다.

Ref.

profile
QA Engineer

0개의 댓글