2

I'm doing an integration test, and the returned value is an array of json objects. The following line of code matches without error:

        mockMvc.perform(MockMvcRequestBuilders.get(uri)
            .param("name", text)
            .accept(MediaType.APPLICATION_JSON))
            .andDo(print())
            .andExpect(status().isOk())
            .andExpect(MockMvcResultMatchers.jsonPath("$[0].name", Matchers.containsString("div3")));

but when I change $[0].name to $[*].name I get an error

java.lang.AssertionError: JSON path "$[*].name"
Expected: a string containing "div3"
 but: was a net.minidev.json.JSONArray (<["Testing Custom Searches div3: 1","Testing Custom Searches div3: 4","Testing Custom Searches div3: 7","Testing Custom Searches div3: 10","Testing Custom Searches div3: 13","Testing Custom Searches div3: 16","Testing Custom Searches div3: 19"]>)

I've been searching around, and not finding an answer...is there a way to check that every *.name element contains a given substring?

1 Answer 1

8

This is because Matchers.containsString() expect a String input but $[*].name returns a net.minidev.json.JSONArray which is an ArrayList.

You can use Matchers.everyItem to match against a list:

MockMvcResultMatchers.jsonPath("$[*].name", Matchers.everyItem(Matchers.containsString("div3")))
Sign up to request clarification or add additional context in comments.

2 Comments

How could we match to a json object?
@MauricioToledo you might consider using a library for that, for example JSONAssert

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.