2

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?

Nikolai Golub
  • 3,327
  • 4
  • 31
  • 61

1 Answers1

4

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

Wilfred Clement
  • 2,674
  • 2
  • 14
  • 29