source

jsonpath를 사용하여 멤버 수를 어떻게 계산합니까?

bestscript 2022. 12. 3. 12:40

jsonpath를 사용하여 멤버 수를 어떻게 계산합니까?

Json Path를 사용하여 멤버 수를 셀 수 있습니까?

Spring 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)));

햄크레스트 버전 1.3과 스프링 테스트 3.2.5를 사용하고 있습니다.풀어주다

hasSize(int) javadoc

주의: 햄크레스트 라이브러리 의존관계와import static org.hamcrest.Matchers.*;hasSize()가 동작합니다.

jsonpath 내의 메서드를 사용할 수도 있습니다.따라서,

mockMvc.perform(get(API_URL))
   .andExpect(jsonPath("$.*", hasSize(2)));

할수있습니다

mockMvc.perform(get(API_URL))
   .andExpect(jsonPath("$.length()", is(2)));

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
    }
})

없으면com.jayway.jsonassert.JsonAssert클래스 패스(저와 같은 경우)에서 다음과 같은 방법으로 테스트하는 것이 가능한 회피책이 될 수 있습니다.

assertEquals(expectedLength, ((net.minidev.json.JSONArray)parsedContent.read("$")).size());

[주의: json의 내용은 항상 배열이라고 가정했습니다]

언급URL : https://stackoverflow.com/questions/13745332/how-to-count-members-with-jsonpath