预期:null 但:是 <[null]> - Hamcrest 和 jsonPath

Bar*_*tek 5 testing hamcrest jsonpath

我想断言来自其余控制器的 json 输出,但我得到“预期:null 但:was <[null]>”。这是我的测试代码:

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

杰森:

{
    "some_string": {
        "errorMessage": null
    }
}
Run Code Online (Sandbox Code Playgroud)

我发现类似的问题How to assertThat Something is null with Hamcrest? ,但这两个答案都不起作用。也许这是由于 jsonPath,导致它在 [] 括号中返回空值?是断言框架的bug吗?

baz*_*a90 4

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

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

根据此处的结果部分 [JSONPath - XPath for JSON]:( http://goessner.net/articles/JsonPath/index.html )

这样就排除了任何问题

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

nullValue 应该按如下方式工作

import static org.hamcrest.CoreMatchers.nullValue;
....
.andExpect(jsonPath("some_string.errorMessage", nullValue()))
Run Code Online (Sandbox Code Playgroud)

或者

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
....
.andExpect(jsonPath("some_string.errorMessage", is(nullValue())))
Run Code Online (Sandbox Code Playgroud)

正如此处找到的答案中所提到的,如何断言 Hamcrest 的某些内容为空?