【问题标题】:How to match objects in an array in no particular order in JsonPath?如何在 JsonPath 中以无特定顺序匹配数组中的对象?
【发布时间】:2022-01-24 04:11:55
【问题描述】:

我正在使用 Spring 和 MockMvc。我正在为特定的控制器响应编写单元测试。它看起来像这样:

{
  "errors": [
    {
      "error": "Bean validation failed.",
      "message": "Bean: UserRegistrationDto. Class/field: userRegistrationDto. Constraint: SafePseudonym."
    },
    {
      "error": "Bean validation failed.",
      "message": "Bean: UserRegistrationDto. Class/field: addressLine1. Constraint: NotNull."
    }
  ]
}

不保证数组errors 的顺序。这部分是因为 Spring 的SmartValidator。我想检查两个对象是否都在数组中,无论顺序如何。

这是我现在的代码:

mvc.perform(post("/registration")
        .contentType(MediaType.APPLICATION_JSON)
        .content(objectMapper.writeValueAsString(validExampleUserRegistrationDtoBuilder().addressLine1(null).pseudonym("oyasuna").build())))
    .andDo(result -> System.out.println(result.getResponse().getContentAsString()))
    .andExpect(status().isBadRequest())
    .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
    .andExpect(jsonPath("$.errors.length()").value(2))
    .andExpectAll(
        jsonPath("$.errors[0].error").value("Bean validation failed."),
        jsonPath("$.errors[0].message").value("Bean: UserRegistrationDto. Class/field: addressLine1. Constraint: NotNull.")
    )
    .andExpectAll(
        jsonPath("$.errors[1].error").value("Bean validation failed."),
        jsonPath("$.errors[1].message").value("Bean: UserRegistrationDto. Class/field: userRegistrationDto. Constraint: SafePseudonym.")
    );

【问题讨论】:

标签: spring spring-boot spring-mvc jsonpath


【解决方案1】:

使用 containsInAnyOrder 进行验证(使用您所需的 json 路径)

    andExpect(jsonPath("$
    .message", containsInAnyOrder("1-st expected message", "2-nd expected message")))
   .andExpect(jsonPath("$
   .error", containsInAnyOrder("1-st expected error, "2-nd expected error")))

【讨论】:

    猜你喜欢
    • 2014-12-16
    • 2018-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-26
    • 1970-01-01
    • 2022-01-28
    • 2021-07-21
    相关资源
    最近更新 更多