Hamcrest检查值是否为空或空数组

问题描述 投票:0回答:1

我有一个代码,该代码返回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: []

此设置中不正确的是什么?

java rest-assured hamcrest
1个回答
0
投票

JSON数组是值的列表,因此请使用empty()而不是emptyArray()

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

何时

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

期望:(空或空集合)

Actual:Wilfred

返回AssertionError

何时

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

正确验证

我有时遇到这个问题,在搜索详细信息时发现this link

© www.soinside.com 2019 - 2024. All rights reserved.