Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare two jsonPath values in MockMvc

I am writing tests for my spring application using MockMvc. Assume that my json result will have the following format:

{
  "available": true,
  "location": [
    {"ID": 1, "path": "local1"},
    {"ID": 2, "path": "local2"},
    {"ID": 3, "path": "local3"}
    ],
  "firstItem": "local1"
}

And I would like to test that if the value of the $.firstItem property will equal to the $.location[0].path or not, actually they are should be equal. Which expectation should I put in the third expect below?

mockMvc.perform(get(url))
                .andExpect(jsonPath("$.available", equalTo(true)))
                .andExpect(jsonPath("$.location", hasSize(3)))
                .andExpect(jsonPath("$.firstItem", ????));

Thank you very much for your help!

like image 740
Ock Avatar asked Mar 28 '18 08:03

Ock


1 Answers

I'm newbie in this area, but this works for me:

mockMvc.perform(get(url))
            .andDo(mvcResult -> {
                String json = mvcResult.getResponse().getContentAsString();
                String a = JsonPath.parse(json).read("$.firstItem").toString();
                String b = JsonPath.parse(json).read("$.location[0].path").toString();
                Assert.isTrue(a.equals(b),"firstItem is different from location[0].path");
            });
like image 76
lojza Avatar answered Sep 30 '22 09:09

lojza