Search code examples
springunit-testingjsonpath

Cannot match the json array element to the value


I want to make a unit test in spring boot. The case is that I have a JSON array and I have to check each array field "details" is equal to "T" or "S"(only "T" or "S" will be accepted). However, when I use Jsonpath & anyof. It gives me an assertion error, any solution can test it? thanks

@Test
public void test() throws Exception {
    mockMvc.perform(MockMvcRequestBuilders.get("/hello"))
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andExpect(jsonPath("$..records[*].abc.details",anyOf(is("T"),is("S"))))
}

This is the json

{
  "records": [
    {
      "id": 1,
      "abc": {
        "details": "T",
        "create-date": "2016-08-24T09:36"
      }
    },
    {
      "id": 5,
      "abc": {
        "detail-type": "S",
        "create-date": "2012-08-27T19:31"
      }
    },
    {
      "id": 64,
      "abc": {
        "detail-type": "S",
        "create-date": "2020-08-17T12:31"
      }
    }
  ]
}

The picture shows the error


Solution

  • it looks like you compare the strings "T" and "S" to a instance of JSONArray. Try out the following matcher:

    MockMvcResultMatchers.jsonPath(
        "$..records[*].abc.details", 
        Matchers.anyOf(
            Matchers.hasItem("T"), 
            Matchers.hasItem("S")
        )
    )
    

    UPDATE:

    according to your comment, you want your test to fail if details contain something else then "T" or "S". Just pass another matcher to jsonPath(). Here you can find examples of matchers working with collections. In your particular case the matcher could look like this:

    MockMvcResultMatchers.jsonPath(
        "$..records[*].abc.details", 
        Matchers.everyItem(
            Matchers.anyOf(
                Matchers.is("T"),
                Matchers.is("S")
            )
        )
    )