반응형
안심.request json에서 값을 추출할 수 있습니까?
다음과 같은 응답이 있습니다.
Response response = expect().statusCode(200).given().body(requestBody).contentType("application/json")
.when().post("/admin");
String responseBody = response.getBody().asString();
응답하는 json Body:
{"user_id":39}
이 값 = 39만 rest-parames 메서드를 사용하여 문자열로 추출할 수 있습니까?
"user_id" 추출에만 관심이 있는 경우 다음과 같이 할 수도 있습니다.
String userId =
given().
contentType("application/json").
body(requestBody).
when().
post("/admin").
then().
statusCode(200).
extract().
path("user_id");
가장 단순한 형태로는 다음과 같습니다.
String userId = get("/person").path("person.userId");
답을 찾았습니다:)
JsonPath 또는 XmlPath(XML이 있는 경우)를 사용하여 응답 본문에서 데이터를 가져옵니다.
내 경우:
JsonPath jsonPath = new JsonPath(responseBody);
int user_id = jsonPath.getInt("user_id");
몇 가지 방법이 있다.개인적으로 사용하는 것은 다음과 같습니다.
단일 값 추출:
String user_Id =
given().
when().
then().
extract().
path("user_id");
둘 이상의 응답이 필요한 경우 전체 응답으로 작업합니다.
Response response =
given().
when().
then().
extract().
response();
String userId = response.path("user_id");
JsonPath를 사용하여 적절한 유형을 추출합니다.
long userId =
given().
when().
then().
extract().
jsonPath().getLong("user_id");
마지막은 값 및 유형과 대조할 때 매우 유용합니다.
assertThat(
when().
then().
extract().
jsonPath().getLong("user_id"), equalTo(USER_ID)
);
안심할 수 있는 문서는 매우 상세하고 충실합니다.원하는 것을 실현하는 방법에는 여러 가지가 있습니다.https://github.com/jayway/rest-assured/wiki/Usage
응답을 클래스로 직렬화하려면 대상 클래스를 정의합니다.
public class Result {
public Long user_id;
}
그리고 그에 대한 대응 지도 작성:
Response response = given().body(requestBody).when().post("/admin");
Result result = response.as(Result.class);
설명서에 기재되어 있는 클래스 패스에 잭슨 또는 Gson이 있어야 합니다.
응답 객체를 직접 사용할 수도 있습니다.
Response response = expect().statusCode(200).given().body(requestBody).contentType("application/json").when().post("/admin");
String userId = response.path("user_id").toString();
JsonPath jsonPathEvaluator = response.jsonPath();
return jsonPathEvaluator.get("user_id").toString();
언급URL : https://stackoverflow.com/questions/21166137/rest-assured-is-it-possible-to-extract-value-from-request-json
반응형
'programing' 카테고리의 다른 글
오브젝트 JSON을 일반 인코더로 시리얼화 (0) | 2023.03.13 |
---|---|
JSON 표현에서의 링크 관계 (0) | 2023.03.13 |
Backbone.js - id vs idAttribute vs cid (0) | 2023.03.13 |
Fetch Response 개체에서 텍스트 가져오기 (0) | 2023.03.13 |
Spring WebFlux에서 요청 및 응답 본문을 기록하는 방법 (0) | 2023.03.13 |