【问题标题】:Spring MockMvc: Assert Json field is either an empty array or not existedSpring MockMvc:断言Json字段是空数组或不存在
【发布时间】:2019-08-28 15:13:46
【问题描述】:

我正在使用MockMvc 测试返回 JSON 内容的 API,并且该 JSON 可能包含一个名为 shares 的字段作为空数组,或者可能根本不存在(我的意思是分享字段)。

JSON 示例:

{
    "id":1234,
     .....
    "shares":[]
}

//or

{
    "id":1234,
    ....
}

如何断言该字段为空或不存在

喜欢:

mvc.perform(
    post("....url.......")
        .andExpect(status().is(200))
        // I need one of the following to be true, but this code will assert both of them, so it will fail
        .andExpect(jsonPath("$.shares").isEmpty())
        .andExpect(jsonPath("$.shares").doesNotExist())

【问题讨论】:

    标签: java junit spring-boot-test mockmvc


    【解决方案1】:

    这是您检查 json 有效负载中不存在该字段的方法。

    .andExpect(jsonPath("$.fieldThatShouldNotExist").doesNotExist())
    

    如果您希望能够测试它是否存在且为空或不存在,您必须编写自己的自定义 Matcher 来创建类似 XOR 的行为。请参阅此答案作为指南。 Testing in Hamcrest that exists only one item in a list with a specific property

    【讨论】:

      【解决方案2】:

      看看 JsonPath OR condition using MockMVC

      .andExpect(jsonPath("$.isPass", anyOf(is(false),is(true))));
      

      【讨论】:

        【解决方案3】:

        如果你有这样的事情:

        { "arrayFieldName": [] }
        

        你可以使用:

        .andExpect( jsonPath( "$.arrayFieldName", Matchers.empty() );
        

        这样更干净。

        【讨论】:

        • 这并没有捕捉到字段不在json正文中的情况。
        • 尽管这不能回答最初的问题,但我发现这很有用。
        【解决方案4】:
        import static org.hamcrest.collection.IsEmptyCollection.empty;
        
        .andExpect(jsonPath("$.isPass",empty() ));
        

        【讨论】:

        • 这并没有捕捉到字段不在json正文中的情况。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-08-26
        • 1970-01-01
        • 2016-06-26
        • 2017-06-07
        • 2021-12-11
        • 2022-01-24
        • 1970-01-01
        相关资源
        最近更新 更多