【问题标题】:Expected: null but: was <[null]> - Hamcrest and jsonPath预期:null 但:是 <[null]> - Hamcrest 和 jsonPath
【发布时间】:2018-04-16 06:53:00
【问题描述】:

我想断言来自休息控制器的 json 输出,但我得到“预期: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,导致它在 [] 括号中返回空值?是断言框架的bug吗?

【问题讨论】:

    标签: testing jsonpath hamcrest


    【解决方案1】:

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

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

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

    这样就排除了

    的任何问题

    因为它在 [] 括号中返回 null 值

    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? 找到的答案中提到的那样

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多