Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asserting array of arrays with JSONPath and spring mvc

Tags:

I'm having difficulty figuring out how to assert with jsonPath in a JSON document response in spring mvc. Perhaps there's a better way of accomplishing this than using jsonPath for this particular scenario. I would like to validate that the links array has a rel item of "self" and that "href" attribute of the object of "self" also has an "href" attribute which is equal to "/". The JSON response looks like this:

 {      "links":[         {            "rel":[               "self"          ],          "href":"/"       },       {            "rel":[               "next"          ],          "href":"/1"       }    ] } 

I tried this where I can see that it has rel [0] has self but I would prefer to not rely on where in the links array and rel array the self is and actually test what that href is at links[rel][self] is "/". Any ideas?

 @Before   public void setup() {     MockitoAnnotations.initMocks(this);     mockMvc = MockMvcBuilders.standaloneSetup(welcomeController).build();   }    @Test   public void givenRootUrl_thenReturnLinkToSelf() throws Exception {     mockMvc.perform(get("/")).andDo(print()).andExpect(status().isOk())         .andExpect(jsonPath("$.links[0].rel[0].", is("self")));   } 
like image 628
Magnus Lassi Avatar asked Sep 02 '14 01:09

Magnus Lassi


2 Answers

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("/")); 
like image 183
Akmal Rakhimov Avatar answered Oct 12 '22 09:10

Akmal Rakhimov


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"))))); 
like image 26
Satrajit A Avatar answered Oct 12 '22 08:10

Satrajit A