Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hamcrest check if value is null or empty array

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?

like image 693
Nikolai Golub Avatar asked Oct 15 '25 04:10

Nikolai Golub


1 Answers

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

like image 148
Wilfred Clement Avatar answered Oct 16 '25 18:10

Wilfred Clement



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!