代码之家  ›  专栏  ›  技术社区  ›  Bartek

应为:null,但:was<[null]>-Hamcrest和jsonPath

  •  1
  • Bartek  · 技术社区  · 6 年前

    我想断言来自rest控制器的json输出,但我得到“预期:null,但:was<[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,因为它在[]括号中返回空值?这是断言框架的错误吗?

    1 回复  |  直到 6 年前
        1
  •  1
  •   bazza90    6 年前

    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())))
    

    如这里的答案所述 How to assertThat something is null with Hamcrest?