unit-testing - JSON 路径没有值
问题描述
如何为以下结合了字符串和数组的 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:'com.jayway.jsonpath.spi.json.JsonSmartJsonProvider',这不是一个 json 对象。
但是,如果我尝试使用 $.accounts[0].id 我得到异常
JSON 路径“$.accounts[0].id”没有值,异常:
预计在路径 $ 中找到具有属性 ['accounts'] 的对象,但找到了 'net.minidev.json.JSONArray'。根据 JsonProvider:'com.jayway.jsonpath.spi.json.JsonSmartJsonProvider',这不是一个 json 对象。
解决方案
该accounts
属性是一个数组,因此 this:$.accounts.id
必须使用索引器,例如:$.accounts[0].id
。
从文档:
[<number> (, <number>)] Array index or indexes
如果您不确定要使用哪个索引,则可以过滤 JSON 并在过滤后的帐户子文档上断言。例如:
$.accounts[?(@.id == 1)].balance
: 返回$1000
$.accounts[?(@.accNbr == 12345)].id
: 返回1
- ... ETC
文档中有更多详细信息,您可以使用JsonPath 评估器来解决这个问题。
推荐阅读
- angular - Observable 类型上不存在属性“发布”
在角 6 - windows - Windows 计时器,如何确定结束时间?
- c# - 临时变量对擦除 GroupBox 背景的影响
- symfony - Symfony 4.1 的 SQLite 环境
- amazon-web-services - 如何处理具有各种“自定义”字段的数据的 ETL / ELT?
- java - JavaFX ObjectOutputStream 只返回 null
- python - OpenPyXL - 如何查询单元格边界?
- swift - swift uipickerview 高度更改不起作用
- swift - 检索最佳分数 Game Center Swift
- typescript - Cocos Creator 和 TypeScript 使用枚举作为属性