3
我正在为使用MockMvc和JsonPath的Spring HATEOAS后端编写单元测试。 为了测试包含在我做类似的响应链接:Spring HATEOAS/MockMvc/JsonPath最佳实践
@Test
public void testListEmpty() throws Exception {
mockMvc.perform(get("/rest/customers"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.links", hasSize(1))) // make sure links only contains self link
.andExpect(jsonPath("$.links[?(@.rel=='self')]", hasSize(1))) // make sure the self link exists 1 time
.andExpect(jsonPath("$.links[?(@.rel=='self')].href", contains("http://localhost/rest/customers{?page,size,sort}"))) // test self link is correct
.andExpect(jsonPath("$.links[?(@.rel=='self')][0].href", is("http://localhost/rest/customers{?page,size,sort}"))) // alternative to test self link is correct
.andExpect(jsonPath("$.content", hasSize(0))); // make sure no content elements exists
}
但是我不知道是否有我应该使用,使一些最佳做法,很容易为自己喜欢的:
- 测试链接包含
http://localhost
感觉不对。我可以使用一些Spring MovkMvc助手来确定主机吗? - 使用JsonPath,很难测试一个数组是否包含其中2个属性具有特定值的元素。 就像这个数组应该包含一个具有特定值的自链接。 有没有更好的方法来测试,然后上面 当测试错误消息字段的验证错误时,这也会发挥作用。
我已经看到类似的技术在以下一些博客文章:
.andExpect(jsonPath("$.fieldErrors[*].path", containsInAnyOrder("title", "description")))
.andExpect(jsonPath("$.fieldErrors[*].message", containsInAnyOrder(
"The maximum length of the description is 500 characters.",
"The maximum length of the title is 100 characters.")));
但这并不是在所有的标题保证了特定的错误信息。 也可能是标题错误地显示了“描述的最大长度为500个字符”。但测试会成功。