0

I am working with Spring and MockMvc. I'm writing a unit test for a specific controller response. It looks something like this:

{
  "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."
    }
  ]
}

There is no guarantee of the order of the array errors. This is partly because of Spring's SmartValidator. I would like to check if both objects are in the the array, regardless of order.

Here is my code now:

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.")
    );
Oliver
  • 1,465
  • 4
  • 17
  • And shortly after posting this, I found the answer: https://stackoverflow.com/questions/26481059/testing-jsonpath-that-array-contains-specfic-objects-in-any-order. – Oliver Dec 23 '21 at 03:55

1 Answers1

1

Use containsInAnyOrder to verify (use your required json path)

    andExpect(jsonPath("$
    .message", containsInAnyOrder("1-st expected message", "2-nd expected message")))
   .andExpect(jsonPath("$
   .error", containsInAnyOrder("1-st expected error, "2-nd expected error")))
Bhushan Uniyal
  • 5,575
  • 2
  • 22
  • 45