我想从rest控制器断言json输出,但我得到“Expected:null但是:是< [null]>”。这是我的测试代码:
mockMvc.perform(post(TEST_ENDPOINT)
.param("someParam", SOMEPARAM)
.andDo(print())
.andExpect(status().is2xxSuccessful())
.andExpect(jsonPath("*.errorMessage").value(IsNull.nullValue()));
JSON:
{
"some_string": {
"errorMessage": null
}
}
我发现了类似的问题How to assertThat something is null with Hamcrest?,但两个答案都没有效果。也许这是由于jsonPath,导致它在[]括号中返回null值?是断言框架的错误吗?
答案 0 :(得分:0)
JSONPath将始终根据文档返回数组,
请注意,jsonPath的返回值是一个数组,也是一个有效的JSON结构。因此,您可能想再次将jsonPath应用于结果结构,或使用您喜欢的数组方法之一对其进行排序。
根据此处的结果部分[JSONPath-JSON的XPath]:(http://goessner.net/articles/JsonPath/index.html)
因此排除
的所有问题因为它在[]中返回空值
nullValue应该如下工作
import static org.hamcrest.CoreMatchers.nullValue;
....
.andExpect(jsonPath("some_string.errorMessage", nullValue()))
或
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
....
.andExpect(jsonPath("some_string.errorMessage", is(nullValue())))
所示的答案中所述