gpt4 book ai didi

Spring HATEOAS/MockMvc/JsonPath 最佳实践

转载 作者:行者123 更新时间:2023-12-04 15:44:05 26 4
gpt4 key购买 nike

我正在使用 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/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com