Spring MVC 5 ResultMatcher jsonPath 空值
Spring MVC 5 ResultMatcher jsonPath null value
将我的休息服务从 Spring Boot 1.5.10 升级到 2.0.0 后,我遇到了之前通过的测试失败。
以下场景:
import org.mockito.internal.matchers.Null;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
...
.andExpect(jsonPath("img").value(Null.NULL))
现在在 Spring MVC 5 中失败并显示以下消息:
java.lang.AssertionError: JSON path "img"
Expected :isNull()
Actual :null
在 Spring MVC 5 中断言 jsonPath
的值为 null
的正确方法是什么?
回答我自己的问题,因为我自己找到了解决方案。
你必须使用正确的匹配器,在我的例子中 org.hamcrest.core.IsNull
所以我不得不改成
import org.hamcrest.core.IsNull;
...
andExpect(jsonPath("img").value(IsNull.nullValue()))
可以使用content().srtring(Matcher matcher) 然后使用IsEmptyString matcher
result.andDo(print())
.andExpect(status().isNoContent())
.andExpect(content().string(IsEmptyString.isEmptyOrNullString()));
2022 年 4 月,Hamcrest 2.2
nullValue() 是可由 org.hamcrest.CoreMatchers.nullValue
导入的独立静态方法。
因此,更新后的解决方案解析为
static import org.hamcrest.core.nullValue;
...
andExpect(jsonPath("img").value(nullValue()))
将我的休息服务从 Spring Boot 1.5.10 升级到 2.0.0 后,我遇到了之前通过的测试失败。
以下场景:
import org.mockito.internal.matchers.Null;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
...
.andExpect(jsonPath("img").value(Null.NULL))
现在在 Spring MVC 5 中失败并显示以下消息:
java.lang.AssertionError: JSON path "img"
Expected :isNull() Actual :null
在 Spring MVC 5 中断言 jsonPath
的值为 null
的正确方法是什么?
回答我自己的问题,因为我自己找到了解决方案。
你必须使用正确的匹配器,在我的例子中 org.hamcrest.core.IsNull
所以我不得不改成
import org.hamcrest.core.IsNull;
...
andExpect(jsonPath("img").value(IsNull.nullValue()))
可以使用content().srtring(Matcher matcher) 然后使用IsEmptyString matcher
result.andDo(print())
.andExpect(status().isNoContent())
.andExpect(content().string(IsEmptyString.isEmptyOrNullString()));
2022 年 4 月,Hamcrest 2.2
nullValue() 是可由 org.hamcrest.CoreMatchers.nullValue
导入的独立静态方法。
因此,更新后的解决方案解析为
static import org.hamcrest.core.nullValue;
...
andExpect(jsonPath("img").value(nullValue()))