如何在JUnit测试中验证复杂的JSONObject?

时间:2018-02-07 17:01:59

标签: java json spring junit

如何正确验证find ~/Library/Android/sdk/build-tools -name "zipalign" JSONObjectJUnit的字段?

@Test

我的意思是,如果在Spring管理的网络服务上进行测试,我可以使用类似如下的{ "persons": [ "adults": [ { "name": ".." "age": .. }, { "name": ".." "age": .. } ] ] }

jsonPath()

但我不是在这里使用网络服务,而是想验证一个json对象。

无论如何我能以某种方式使用mockMvc.perform(get("/")).andDo(print()).andExpect(status().isOk()) .andExpect(jsonPath("$.persons[0].adults[0].name", is("John"))); 春天的方法,还是有类似的技巧?

2 个答案:

答案 0 :(得分:3)

如果没有Spring包装,你可以使用Jayway JsonPath

例如:

String json = "{\n" +
        "  \"persons\": [\n" +
        "    {\n" +
        "      \"adults\": [\n" +
        "        {\n" +
        "          \"name\": \"John\",\n" +
        "          \"age\": 25\n" +
        "        },\n" +
        "        {\n" +
        "          \"name\": \"Jill\",\n" +
        "          \"age\": 36\n" +
        "        }\n" +
        "      ]\n" +
        "    }\n" +
        "  ]\n" +
        "}";

DocumentContext documentContext = JsonPath.parse(json);

assertThat(documentContext.read("$.persons[0].adults[0].name"), is("John"));
assertThat(documentContext.read("$.persons[0].adults[1].age"), is(36));
assertThat(documentContext.read("$.persons.length()"), is(1));
assertThat(documentContext.read("$.persons[0].adults.length()"), is(2));

或者,您可以在JsonPath之上使用json-path-assert来添加Hamcrest匹配器,如下所示:

assertThat(json, hasJsonPath("$.persons[0].adults[0].name", is("John")));
assertThat(json, hasJsonPath("$.persons[0].adults[1].age", is(36)));

Maven协调:

<!-- jayway jsonpath -->
<dependency>
    <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path</artifactId>
    <version>2.3.0</version>
    <scope>test</scope>
</dependency>

<!-- json-path-assert -->
<dependency>
    <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path-assert</artifactId>
    <version>2.2.0</version>
    <scope>test</scope>
</dependency>

答案 1 :(得分:0)

有一种替代方法可以根据预期值验证 JSON 回复。您可以使用 JSONassert

示例:

final MvcResult result = mockMvc.perform(get("/"))
                                .andDo(print())
                                .andExpect(status().isOk())
                                .andReturn();

final String json = result.getResponse().getContentAsString();
final String expected = "{field:'value', anotherField:true}";

JSONAssert.assertEquals(expected, json, true);

JSONassert 提供多种验证模式,包括自定义比较器。

这是验证 JSON 输出的非常方便的方法。在许多情况下,它显着减少了单元测试类的大小,并为您提供了预期 JSON 对象的可视化表示。

相关问题