Testing 应为:null,但:was<;[null]>;-汉克雷斯特和杰森帕斯

Testing 应为:null,但:was<;[null]>;-汉克雷斯特和杰森帕斯,testing,jsonpath,hamcrest,Testing,Jsonpath,Hamcrest,我想断言来自rest控制器的json输出,但我得到了“Expected:null,but:was”。这是我的测试代码: mockMvc.perform(post(TEST_ENDPOINT) .param("someParam", SOMEPARAM) .andDo(print()) .andExpect(status().is2xxSuccessful()) .andExpect(jsonPath(

我想断言来自rest控制器的json输出,但我得到了“Expected:null,but:was”。这是我的测试代码:

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


我发现了类似的问题,但两个答案都不起作用。也许这是由于jsonPath,因为它在[]括号中返回空值?这是断言框架的错误吗?

JSONPath将根据文档始终返回一个数组

请注意,jsonPath的返回值是一个数组,也是一个有效的JSON结构。因此,您可能希望再次将jsonPath应用于结果结构,或者使用您最喜欢的数组方法之一作为排序

根据这里的结果部分[JSONPath-XPath for JSON]:()

这样就排除了任何问题

导致它在[]括号中返回空值

nullValue的工作原理如下

import static org.hamcrest.CoreMatchers.nullValue;
....
.andExpect(jsonPath("some_string.errorMessage", 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())))