gpt4 book ai didi

java - 单元测试 Spring MVC Rest 服务 : array jsonPath

转载 作者:搜寻专家 更新时间:2023-11-01 02:37:40 25 4
gpt4 key购买 nike

在我的 Spring Controller 中,我有一个返回以下 json 的方法:

[
{
"id": 2,
"dto": null,
"user": {
"userId": 2,
"firstName": "Some",
"lastName": "Name",
"age": 100,
"aboutMe": "boring"
},
"isYoung": false,
"isOk": false
}
]

我正在尝试为这个 getter 编写一个测试。这是我的测试:

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

显然我没弄对:

虽然如果我只为 $[0].id 运行测试,测试通过。但是对于所有其他情况(对于嵌套用户对象和 isYoung 字段和 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)));
}

关于java - 单元测试 Spring MVC Rest 服务 : array jsonPath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43378127/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com