我很难弄清楚如何在 spring mvc 的 JSON 文档响应中使用 jsonPath 进行断言。对于这个特定场景,也许有比使用 jsonPath 更好的方法来完成此任务。我想验证 links 数组是否具有“self”的 rel 项,并且“self”对象的“href”属性也具有等于“/”的“href”属性。 JSON 响应如下所示:
{
"links":[
{
"rel":[
"self"
],
"href":"/"
},
{
"rel":[
"next"
],
"href":"/1"
}
]
}
我尝试了这个,我可以看到它有 rel [0] 有 self,但我宁愿不依赖于 links 数组和 rel 数组中 self 的位置,而是实际测试该 href 在 links[rel][self 中的位置] 是 ”/”。 有什么想法吗?
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.standaloneSetup(welcomeController).build();
}
@Test
public void givenRootUrl_thenReturnLinkToSelf() throws Exception {
mockMvc.perform(get("/")).andDo(print()).andExpect(status().isOk())
.andExpect(jsonPath("$.links[0].rel[0].", is("self")));
}
添加几个 andExpect 方法怎么样?类似于:
mockMvc.perform(get("/")).andDo(print()).andExpect(status().isOk())
.andExpect(jsonPath("$.links[0].rel[0]", is("self")))
.andExpect(jsonPath("$.links[0].href[0]", is("/"));
我想如果你不想硬编码数组索引值,你可以这样做
MockMvc.perform(get("/"))
.andDo(print()).andExpect(status().isOk())
.andExpect(jsonPath("$.links[*].rel").value(Matchers.containsInAnyOrder(Matchers.containsInAnyOrder(Matchers.is("self")))));
接受的答案对我来说看起来不错。但我对junit4不熟悉。因此,我将在此处添加如何使用 Junit5 测试典型场景。
mockMvc.perform(get("/"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(jsonPath("$.links", hasSize(2)))
.andExpect(jsonPath("$.links[0].rel[0]")
.value("self"))
.andExpect(jsonPath("$.links[0].href[0]")
.value("/"))
我将在这里添加静态导入(对于初学者),因为当我第一次工作时,我必须弄清楚多个导入中的哪些导入。
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import static org.hamcrest.Matchers.hasSize;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.hamcrest.CoreMatchers.is;
希望这对某人有帮助。尤其是单元测试新手:)
你可以尝试一下:
mockMvc.perform(get("/")).andDo(print()).andExpect(status().isOk())
.andExpect(jsonPath("$.links[*].rel[*]", containsInAnyOrder("self")))
.andExpect(jsonPath("$.links[*].href[*]", containsInAnyOrder("/")))
我知道一篇很老的帖子,你可能已经弄清楚了,但是为了为了新开发者想知道这个问题,就像我一样。
您可以使用以下内容。
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasSize;
.......AdditionalCode
.andExpect(jsonPath("$.path").isArray())
.andExpect(jsonPath("$.path").value(hasSize(2))
.andExpect(jsonPath("$.path").value(hasItem("self!"))
来源=> https://mkyong.com/spring-boot/spring-test-how-to-test-a-json-array-in-jsonpath/