Asserting array of arrays with JSONPath and spring mvc
you can try :
mockMvc.perform(get("/")).andDo(print()).andExpect(status().isOk())
.andExpect(jsonPath("$.links[*].rel[*]", containsInAnyOrder("self")))
.andExpect(jsonPath("$.links[*].href[*]", containsInAnyOrder("/")))
I guess you could do it like this if you don't want to hardcode array index value
MockMvc.perform(get("/"))
.andDo(print()).andExpect(status().isOk())
.andExpect(jsonPath("$.links[*].rel").value(Matchers.containsInAnyOrder(Matchers.containsInAnyOrder(Matchers.is("self")))));
How about adding several andExpect methods? Something similar to:
mockMvc.perform(get("/")).andDo(print()).andExpect(status().isOk())
.andExpect(jsonPath("$.links[0].rel[0]", is("self")))
.andExpect(jsonPath("$.links[0].href[0]", is("/"));
The Accepted answer looks alright to me. But I am not familiar with junit4. Therefore I will add here how I would test a typical scenario using Junit5.
mockMvc.perform(get("/"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(jsonPath("$.links", hasSize(2)))
.andExpect(jsonPath("$.links[0].rel[0]")
.value("self"))
.andExpect(jsonPath("$.links[0].href[0]")
.value("/"))
I will here add static imports(in case of a beginner) because when first I was working of I had to figure which imports within several imports.
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import static org.hamcrest.Matchers.hasSize;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
Hope this is helpful for someone. especially someone new to unit testing :)