问题
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