我正在使用 MockMvc 和 JsonPath 为 Spring HATEOAS 后端编写单元测试。为了测试响应中包含的链接,我正在做类似的事情:
@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 个字符”。但测试会成功。