Hamcrest check if value is null or empty array

半世苍凉 提交于 2021-02-11 15:41:43

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/61409442/hamcrest-check-if-value-is-null-or-empty-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!