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

1 Answer 1

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")))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.