4 java spring integration-testing spring-mvc mockmvc
在我的Spring控制器中,我有一个返回以下json的方法:
[
{
"id": 2,
"dto": null,
"user": {
"userId": 2,
"firstName": "Some",
"lastName": "Name",
"age": 100,
"aboutMe": "boring"
},
"isYoung": false,
"isOk": false
}
]
Run Code Online (Sandbox Code Playgroud)
我正在尝试为此吸气剂编写测试。这是我的测试:
@Test
public void getterMethod() throws Exception{
mockMvc.perform(get("/path?id=1")).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$[0].id", is(2)))
.andExpect(jsonPath("$[2].user.userId", is(2)))
.andExpect(jsonPath("$[2].user.firstName", is("Giorgos")))
.andExpect(jsonPath("$[2].user.lastName", is("Ant")))
.andExpect(jsonPath("$[3].isYoung", is(false)))
.andExpect(jsonPath("$[4].isOk", is(false)));
}
Run Code Online (Sandbox Code Playgroud)
显然我做错了:
尽管如果仅对$ [0] .id运行测试,则测试通过。但是对于所有其他情况(对于嵌套的用户对象以及isYoung fiels和isOk),我遇到了数组索引异常错误。
有什么想法吗?
测试应该是:
@Test
public void getterMethod() throws Exception{
mockMvc.perform(get("/path?id=1")).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$[0].id", is(2)))
.andExpect(jsonPath("$[0].user.userId", is(2)))
.andExpect(jsonPath("$[0].user.firstName", is("Some")))
.andExpect(jsonPath("$[0].user.lastName", is("Name")))
.andExpect(jsonPath("$[0].isYoung", is(false)))
.andExpect(jsonPath("$[0].isOk", is(false)));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2791 次 |
| 最近记录: |