Expected: null but: was <[null]> - Hamcrest and jsonPath
Asked Answered
K

1

6

I would like to assert json output from rest controller, but I get "Expected: null but: was <[null]>". This is my testing code:

mockMvc.perform(post(TEST_ENDPOINT)
            .param("someParam", SOMEPARAM)
            .andDo(print())
            .andExpect(status().is2xxSuccessful())
            .andExpect(jsonPath("*.errorMessage").value(IsNull.nullValue())); 

Json:

{
    "some_string": {
        "errorMessage": null
    }
}

I found similar question How to assertThat something is null with Hamcrest?, but neither answers do work. Maybe this is due to jsonPath, cause it return null value in [] brackets? Is it bug of asserting framework?

Kopeisk answered 16/4, 2018 at 6:53 Comment(0)
T
6

JSONPath will always return an array according to the documentation,

Please note, that the return value of jsonPath is an array, which is also a valid JSON structure. So you might want to apply jsonPath to the resulting structure again or use one of your favorite array methods as sort with it.

As per the results section here [JSONPath - XPath for JSON]:(http://goessner.net/articles/JsonPath/index.html)

So that rules out any issues with

cause it return null value in [] brackets

nullValue should work as follows

import static org.hamcrest.CoreMatchers.nullValue;
....
.andExpect(jsonPath("some_string.errorMessage", nullValue()))

or

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
....
.andExpect(jsonPath("some_string.errorMessage", is(nullValue())))

As mentioned in the answers found here How to assertThat something is null with Hamcrest?

Ternate answered 28/8, 2018 at 14:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.