2

I'm using MockMvc to test an API which returns JSON content, and that JSON may contain a field called shares as an empty array, or may not be existed at all (I mean shares field).

JSON sample:

{
    "id":1234,
     .....
    "shares":[]
}

//or

{
    "id":1234,
    ....
}

How can I assert that this field is either empty or not existed

like:

mvc.perform(
    post("....url.......")
        .andExpect(status().is(200))
        // I need one of the following to be true, but this code will assert both of them, so it will fail
        .andExpect(jsonPath("$.shares").isEmpty())
        .andExpect(jsonPath("$.shares").doesNotExist())
Fábio Nascimento
  • 2,644
  • 1
  • 21
  • 27
Nosairat
  • 482
  • 9
  • 20

5 Answers5

3

This is how you can check that the field does NOT exist in the json payload.

.andExpect(jsonPath("$.fieldThatShouldNotExist").doesNotExist())

If you wanted to be able to test for if it exists and is empty OR it doesn't exist, you'd have to write your own custom Matcher to create an XOR like behavior. See this answer as a guide. Testing in Hamcrest that exists only one item in a list with a specific property

Kevin M
  • 2,717
  • 4
  • 26
  • 31
1

Have a look at JsonPath OR condition using MockMVC

.andExpect(jsonPath("$.isPass", anyOf(is(false),is(true))));
i.bondarenko
  • 3,442
  • 3
  • 11
  • 21
0

If you have something like this:

{ "arrayFieldName": [] }

You can use:

.andExpect( jsonPath( "$.arrayFieldName", Matchers.empty() );

that is cleaner.

marcello
  • 165
  • 2
  • 9
0

In order to catch the case where the field isn't in the json body at all, you can use doesNotHaveJsonPath():

.andExpect(jsonPath("$.fieldThatShouldNotExistOrEvenBeNull").doesNotHaveJsonPath())

So if your shares field isn't present in the body, this matcher will pass. If it is present, this matcher will fail.

-1
import static org.hamcrest.collection.IsEmptyCollection.empty;

.andExpect(jsonPath("$.isPass",empty() ));
Dharman
  • 30,962
  • 25
  • 85
  • 135