【问题标题】:Spring HATEOAS / MockMvc / JsonPath best practicesSpring HATEOAS / MockMvc / JsonPath 最佳实践
【发布时间】:2014-08-29 14:46:56
【问题描述】:

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

【问题讨论】:

    标签: spring rest spring-data-rest spring-hateoas


    【解决方案1】:

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

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

    您可以在我的帖子中找到一些示例:Implementing HAL hypermedia REST API using Spring HATEOAS。 另请查看tests in the sample project

    【讨论】:

      【解决方案2】:

      解决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}"))))
      

      【讨论】:

        猜你喜欢
        • 2015-03-18
        • 2015-09-11
        • 2020-03-08
        • 2010-12-22
        • 1970-01-01
        • 2015-04-19
        • 2010-11-07
        • 2011-05-18
        • 1970-01-01
        相关资源
        最近更新 更多