【发布时间】:2018-05-25 07:48:28
【问题描述】:
如何为下面的字符串和数组组合的 JSON 编写 mockMVC 测试。
{
"id":1,
"firstName":"NPA",
"lastName":"TAS",
"mobile":"123454321",
"email":"ABCD@GMAIL.COM",
"accounts":[
{
"id":1,
"balance":"$1000",
"custid":"1",
"accNbr":"12345"
}
]
}
我的代码:
@Test
public void testJson() throws Exception {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
mockMvc.perform(get("/acc/1")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$.accounts.id", Matchers.is(1)))
.andExpect(jsonPath("$.accounts.balance", Matchers.is("$1000")))
.andExpect(jsonPath("$.accounts.accNbr", Matchers.is("12345")))
.andExpect(jsonPath("$.accounts.custid", Matchers.is("1")))
.andExpect(jsonPath("$.*", Matchers.hasSize(4)));
}
我得到了异常
JSON 路径“$.accounts.id”处没有值,异常:
预期在路径 $ 中找到具有属性 ['accounts'] 的对象,但找到了 'net.minidev.json.JSONArray'。根据 JsonProvider,这不是一个 json 对象:'com.jayway.jsonpath.spi.json.JsonSmartJsonProvider'。
但是,如果我尝试使用 $.accounts[0].id 我会遇到异常
JSON 路径“$.accounts[0].id”处没有值,异常:
预期在路径 $ 中找到具有属性 ['accounts'] 的对象,但找到了 'net.minidev.json.JSONArray'。根据 JsonProvider,这不是一个 json 对象:'com.jayway.jsonpath.spi.json.JsonSmartJsonProvider'。
【问题讨论】:
-
因为有一个账户数组。因此,您应该将 $.accounts[0].id 用于数组帐户中的第一个帐户。
-
@KeyMarker00 $.accounts[0].id 也不起作用
-
如果您在online evaulator 中使用您的问题中提供的 JSON 和此表达式
$.accounts[0].id,那么您将得到一个有效的答案,因此最可能的解释是:“ @KeyMarker00 $.accounts[0].id 也不起作用”是get("/acc/1")生成的 JSON 与您在问题中包含的 JSON 不匹配。我怀疑该端点生成的 actula JSON 可能如下所示:[{"id":1, "firstName":"NPA", ...}]即一个子文档数组,每个子文档都包含一个帐户 [],而不是一个包含帐户 [] 的单个文档。
标签: unit-testing spring-mvc mockito jsonpath mockmvc