Spring HATEOAS/MockMvc/JsonPath 最佳实践

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

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

    最佳答案

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

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

    您可能会在我的帖子中找到一些示例:Implementing HAL hypermedia REST API using Spring HATEOAS .
    还看tests in the sample project .

    关于Spring HATEOAS/MockMvc/JsonPath 最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25570728/

    相关文章:

    java - 在 Spring-boot 中设置默认 Activity 配置文件

    iOS、REST API - Facebook 登录

    用于实体关联更新的 Spring Data REST 事件

    java - Spring 启动: constructor injection with xml gives "there is already n bean method"

    java - 如何为多个 servlet 配置 spring security?

    java - 如果主机离线,重试 java RestTemplate HTTP 请求

    java - 将剩余发布请求映射到对象

    rest - 如何在 Spring MVC 中为 REST API 实现 HTTP 'OPTIONS' 动词?

    Spring 数据休息: repository multiple value request parameters

    java - 通过 REST Controller 使用 Spring Data JPA 和 QueryDsl 的异常