6

我正在使用 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 个字符”。但测试会成功。

4

2 回答 2

2

您可以使用Traverson(包含在 Spring HATEOAS 中)来遍历测试中的链接。

如果您使用的是 Spring Boot,我会考虑使用@WebIntegrationTest("server.port=0")而不是MockMvc,因为在某些情况下,我遇到的行为与实际应用程序略有不同。

您可以在我的一篇文章中找到一些示例:使用 Spring HATEOAS 实现 HAL 超媒体 REST API。另请查看示例项目中的测试

于 2016-05-20T18:07:08.250 回答
0

http://localhost在不牺牲测试数组元素上的两个属性约束的需要的情况下解决问题的一种方法是使用org.hamcrest.CoreMatchers.hasItem(org.hamcrest.Matcher nestedMatcher)匹配器。您在上面显示的测试现在变为:

.andExpect(jsonPath("$.links[?(@.rel=='self')].href", hasItem(endsWith("/rest/customers{?page,size,sort}"))))
.andExpect(jsonPath("$.links[?(@.rel=='self')][0].href", hasItem(endsWith("/rest/customers{?page,size,sort}"))))
于 2019-05-31T23:40:08.147 回答