springspring-mvcjunitmockitomockmvc

How to do an OR condition on result, when using Spring MockMVC?


Currently I have below -

.andExpect(org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath("$.message",
                            org.hamcrest.Matchers.equalTo("storeCode cannot be blank text; storeCode cannot be null")));

How can i add an OR condition to the above, something like below (ofcourse, below does not work)

.andExpect(org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath("$.message",
                            org.hamcrest.Matchers.equalTo("storeCode cannot be blank text; storeCode cannot be null").OR.equalTo("storeCode cannot be null; storeCode cannot be blank text")));

Solution

  • You can use the either, anyOf, or oneOf matchers.

    either:

    .andExpect(
        MockMvcResultMatchers.jsonPath(
            "$.message",
            Matchers.either(Matchers.equalTo("storeCode cannot be blank text; storeCode cannot be null"))
            .or(Matchers.equalTo("storeCode cannot be null; storeCode cannot be blank text"))));
    

    anyOf:

    .andExpect(
        MockMvcResultMatchers.jsonPath(
            "$.message",
            Matchers.anyOf(
                Matchers.equalTo("storeCode cannot be blank text; storeCode cannot be null"),
                Matchers.equalTo("storeCode cannot be null; storeCode cannot be blank text"))));
    

    oneOf:

    .andExpect(
        MockMvcResultMatchers.jsonPath(
            "$.message",
            Matchers.oneOf(
                "storeCode cannot be blank text; storeCode cannot be null",
                "storeCode cannot be null; storeCode cannot be blank text")));
    

    Or use a regular expression with matchesPattern:

    .andExpect(
        MockMvcResultMatchers.jsonPath(
            "$.message",
            Matchers.matchesPattern(
                "storeCode cannot be blank text; storeCode cannot be null|storeCode cannot be null; storeCode cannot be blank text"))));