Oliver
Oliver

Reputation: 1645

How to match objects in an array in no particular order in JsonPath?

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.")
    );

Upvotes: 0

Views: 1538

Answers (1)

Bhushan Uniyal
Bhushan Uniyal

Reputation: 5703

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")))

Upvotes: 1

Related Questions