Hamcrest 检查值是否为空或空数组 [英] Hamcrest check if value is null or empty array

查看:71
本文介绍了Hamcrest 检查值是否为空或空数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个返回 JSON 的代码,其中一个字段可能为 null 或空数组.

我有这个代码要检查:

import static org.hamcrest.core.AnyOf.anyOf;导入静态 org.hamcrest.CoreMatchers.nullValue;导入静态 org.hamcrest.Matchers.blankOrNullString;//io.restassured.responsegetResponse.then().assertThat().body("entity.fields", anyOf(nullValue(), emptyArray()))

但输出不清楚

java.lang.AssertionError: 1 期望失败.JSON 路径 entity.fields 不匹配.预期:(空或空数组)实际的: []

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

解决方案

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

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

什么时候

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

<块引用>

预期:(空或空集合)

实际:威尔弗雷德

断言错误返回

什么时候

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

适当的验证

我曾经遇到过这个问题,找到了这个链接 搜索详情时

I have a code, which returns JSON, where one field might be null or empty array.

I have this code to check:

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

But output is unclear

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

What is incorreect in this setup?

解决方案

JSON array are list of values, so instead of emptyArray() use empty()

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

When

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

Expected: (null or an empty collection)

Actual: Wilfred

AssertionError returned

When

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

Proper validation

I had this issue sometime back, found this link while searching for details

这篇关于Hamcrest 检查值是否为空或空数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆