4

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())

5 Answers 5

5

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

Sign up to request clarification or add additional context in comments.

Comments

2

If you have something like this:

{ "arrayFieldName": [] }

You can use:

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

that is cleaner.

2 Comments

This doesn't catch the case where the field is not in the json body.
Even though this doesn't answer the original question, I found this useful.
1

Have a look at JsonPath OR condition using MockMVC

.andExpect(jsonPath("$.isPass", anyOf(is(false),is(true))));

Comments

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.

Comments

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

.andExpect(jsonPath("$.isPass",empty() ));

1 Comment

This doesn't catch the case where the field is not in the json body.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.