1

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

1 Answer 1

1

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

2 Comments

If I not enter "T" or "S", it still can pass the unit test
@EdthinChung updated my answer. Just try out different matchers.

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.