Spring MVC 5 ResultMatcher jsonPath null value
Asked Answered
P

3

9

After upgrading my rest service from Spring Boot 1.5.10 to 2.0.0 I encountered my tests failing which passed before.

Following Scenario:

import org.mockito.internal.matchers.Null;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;

...

.andExpect(jsonPath("img").value(Null.NULL))

Fails now in Spring MVC 5 with following message:

java.lang.AssertionError: JSON path "img"
Expected :isNull() Actual :null

What is the correct way in Spring MVC 5 to assert that the value of the jsonPath is null?

Perkin answered 14/3, 2018 at 14:4 Comment(3)
Are you using jayway lib for jsonpath? Can you please show the name package name for jsonpath ?Islet
I am using org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;Perkin
alternate way is to use new JsonPathExpectationsHelper("$.img").assertValueIsEmpty(jsonContent);Islet
P
27

Answering my own question as I found the solution by myself.

You have to use the correct Matcher, in my case org.hamcrest.core.IsNull

So I had to change to

import org.hamcrest.core.IsNull;
...
andExpect(jsonPath("img").value(IsNull.nullValue()))
Perkin answered 14/3, 2018 at 14:46 Comment(0)
C
4

April 2022, Hamcrest 2.2

nullValue() is a standalone static method importable by org.hamcrest.CoreMatchers.nullValue.

So, updated solution resolves to

static import org.hamcrest.core.nullValue;
...
andExpect(jsonPath("img").value(nullValue()))
Chippewa answered 25/4, 2022 at 10:40 Comment(0)
T
2

You can use content().srtring(Matcher matcher) and then use IsEmptyString matcher

result.andDo(print())
      .andExpect(status().isNoContent())
      .andExpect(content().string(IsEmptyString.isEmptyOrNullString()));
Tanhya answered 19/5, 2018 at 21:4 Comment(2)
It's not the same. Your solution will verify that response doesn't have any content at all, but the required solution, which was provided by @Perkin himself, should verify that only one field from the response Json object is NULL. It's two definitely different checks.Tambourin
isEmptyOrNullString() was deprecated you should use emptyOrNullString()Fearless

© 2022 - 2024 — McMap. All rights reserved.