javajsonjunitjsonpathhamcrest

Matching Boolean true value using jsonPath


I am trying to write a JUnit test, which checks the value of received JSON. I access these values in the JSON using jsonPath. I want to check if a value is true. For simple jsonPaths, it works for me, but when I write more complex jsonPath query, it does not and I am getting this Assertion Error:

Expected: is <true>
but: was <[true]>

My JSON:

{...
,"trips":
  [
    {...
    ,"employee":{"name":"Ordinary Joe","login":"joe","contractor":true}
    ,...
    },
    ...
  ],
 ...
}

Problematic assertion

.andExpect(jsonPath("$.trips[?(@.employee.login=='joe')].employee.contractor", is(true)));

What I've tried

I tried to match the value also with new Boolean(true), boolean[] array with one true value and after examination of is() matcher also with String.valueOf(true) however it also did not match.

My question

How should I correctly match this true value? What exactly these [] braces mean in the test output?


Solution

  • In the further investigation, I actually found that jsonPath somehow converts the obtained true value to a JsonArray with one item and therefore it is not possible to match it with is(true) matcher. I am not sure why JsonPath does so.

    I found the following working workaround using hasItem matcher instead:

    .andExpect(jsonPath("$.trips[?(@.employee.login=='joe')].employee.contractor", hasItem(true)))
    .andExpect(jsonPath("$.trips[?(@.employee.login=='joe')].employee.contractor", not(hasItem(false))))