【问题标题】:Hamcrest check if value is null or empty arrayHamcrest 检查值是否为空或空数组
【发布时间】:2020-04-24 13:23:45
【问题描述】:

我有一个代码,它返回 JSON,其中一个字段可能是 null 或空数组。

我有这段代码要检查:

import static org.hamcrest.core.AnyOf.anyOf;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.Matchers.blankOrNullString;

// io.restassured.response
getResponse.then()
   .assertThat()
   .body("entity.fields", anyOf(nullValue(), emptyArray()))

但输出不清楚

java.lang.AssertionError: 1 expectation failed.
JSON path entity.fields doesn't match.
Expected: (null or an empty array)
  Actual: []

这个设置有什么不正确的地方?

【问题讨论】:

  • 当你说 json 有空数组时,你的意思是它是这种格式吗? { "entity": { "fields": [] } } 和 null 的情况下,那么这种格式? { "entity": { "fields": null } }
  • getResponse的实际值是多少?
  • @WilfredClement,你是对的,可能是[]null

标签: java rest-assured hamcrest


【解决方案1】:

JSON 数组是值的列表,所以用 empty() 代替 emptyArray()

assertThat().body("entity.fields", anyOf(nullValue(),empty()));

什么时候

{"entity":{"fields":"Wilfred"}}

预期:(null 或空集合)

实际:威尔弗雷德

AssertionError 返回

什么时候

{"entity":{"fields":null}} or {"entity":{"fields":[]}}

正确验证

我曾经遇到过这个问题,在搜索详细信息时找到了this link

【讨论】:

    猜你喜欢
    • 2011-11-04
    • 1970-01-01
    • 2012-07-29
    • 1970-01-01
    • 2017-09-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多