jsonpath로 회원 수?
JsonPath를 사용하여 회원 수를 계산할 수 있습니까?
스프링 mvc 테스트를 사용하여 생성하는 컨트롤러를 테스트하고 있습니다.
{"foo": "oof", "bar": "rab"}
와
standaloneSetup(new FooController(fooService)).build()
.perform(get("/something").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk())
.andExpect(jsonPath("$.foo").value("oof"))
.andExpect(jsonPath("$.bar").value("rab"));
생성 된 json에 다른 멤버가 없는지 확인하고 싶습니다. jsonPath를 사용하여 개수를 세는 것이 좋습니다. 가능할까요? 대체 솔루션도 환영합니다.
배열의 크기를 테스트하려면 :jsonPath("$", hasSize(4))
개체의 구성원을 계산하려면 :jsonPath("$.*", hasSize(4))
즉, API가 4 개 항목 의 배열 을 반환하는지 테스트 합니다.
허용 된 값 : [1,2,3,4]
mockMvc.perform(get(API_URL))
.andExpect(jsonPath("$", hasSize(4)));
API가 2 개의 멤버를 포함 하는 객체 를 반환하는지 테스트하려면 :
허용 된 값 : {"foo": "oof", "bar": "rab"}
mockMvc.perform(get(API_URL))
.andExpect(jsonPath("$.*", hasSize(2)));
Hamcrest 버전 1.3 및 Spring Test 3.2.5를 사용하고 있습니다 .RELEASE
참고 : hamcrest-library 종속성을 포함하고 import static org.hamcrest.Matchers.*;
hasSize ()가 작동하도록해야합니다.
다음 과 같이 또는 같은 JsonPath 함수 를 사용할 수 있습니다 .size()
length()
@Test
public void givenJson_whenGetLengthWithJsonPath_thenGetLength() {
String jsonString = "{'username':'jhon.user','email':'jhon@company.com','age':'28'}";
int length = JsonPath
.parse(jsonString)
.read("$.length()");
assertThat(length).isEqualTo(3);
}
또는 단순히 파싱 net.minidev.json.JSONObject
하여 크기를 가져옵니다.
@Test
public void givenJson_whenParseObject_thenGetSize() {
String jsonString = "{'username':'jhon.user','email':'jhon@company.com','age':'28'}";
JSONObject jsonObject = (JSONObject) JSONValue.parse(jsonString);
assertThat(jsonObject)
.size()
.isEqualTo(3);
}
실제로 두 번째 접근 방식은 첫 번째 접근 방식보다 성능이 더 좋아 보입니다. JMH 성능 테스트를했고 다음과 같은 결과를 얻었습니다.
| Benchmark | Mode | Cnt | Score | Error | Units |
|-------------------------------------------------|-------|-----|-------------|--------------|-------|
| JsonPathBenchmark.benchmarkJSONObjectParse | thrpt | 5 | 3241471.044 | ±1718855.506 | ops/s |
| JsonPathBenchmark.benchmarkJsonPathObjectLength | thrpt | 5 | 1680492.243 | ±132492.697 | ops/s |
오늘 직접 처리했습니다. 이것이 사용 가능한 어설 션에서 구현 된 것 같지 않습니다. 그러나 org.hamcrest.Matcher
객체 를 전달하는 방법이 있습니다. 이를 통해 다음과 같은 작업을 수행 할 수 있습니다.
final int count = 4; // expected count
jsonPath("$").value(new BaseMatcher() {
@Override
public boolean matches(Object obj) {
return obj instanceof JSONObject && ((JSONObject) obj).size() == count;
}
@Override
public void describeTo(Description description) {
// nothing for now
}
})
jsonpath 내부에서 메서드를 사용할 수도 있으므로 대신
mockMvc.perform(get(API_URL))
.andExpect(jsonPath("$.*", hasSize(2)));
넌 할 수있어
mockMvc.perform(get(API_URL))
.andExpect(jsonPath("$.length()", is(2)));
if you don't have com.jayway.jsonassert.JsonAssert
on your classpath (which was the case with me), testing in the following way may be a possible workaround:
assertEquals(expectedLength, ((net.minidev.json.JSONArray)parsedContent.read("$")).size());
[note: i assumed that the content of the json is always an array]
참고URL : https://stackoverflow.com/questions/13745332/count-members-with-jsonpath
'IT story' 카테고리의 다른 글
SQL Server에서는 언제 GO를 사용해야하며 언제 세미콜론을 사용해야합니까? (0) | 2020.09.02 |
---|---|
복제 가능 Java 정보 (0) | 2020.09.02 |
Python에서 목록의 첫 번째 위치에 삽입 (0) | 2020.09.02 |
왜이 구조체 크기가 2가 아닌 3입니까? (0) | 2020.09.02 |
자바 스크립트로 모든 인라인 스타일을 지우고 CSS 스타일 시트에 지정된 스타일 만 남기려면 어떻게해야합니까? (0) | 2020.09.02 |