11

How can I test for an empty JSON response from a rest endpoint. I was hoping for something along the lines:

    ResultActions actions = mockMvc.perform(..);
    actions.andExpect(jsonPath("$", empty()));

obviously this fails as {} is not exactly empty. Any advice?

6 Answers 6

16

Try this one:

 ResultActions actions = mockMvc.perform(..);
 actions.andExpect(content().string("[]"));
Sign up to request clarification or add additional context in comments.

Comments

3

This worked for me:

ResultActions actions = mockMvc.perform(..);
actions.andExpect(content().string(""));

Comments

3

In JSON, {} is a non-null, but empty, object. This translates into Java as an empty map. You can validate that a JSON element is non-null and empty like this:

actions.andExpect(jsonPath("$").value(Collections.EMPTY_MAP))

Comments

1

The exists() method worked well for me.

this.mockMvc.perform(get("....")).andExpect(jsonPath("$").exists());

Comments

1

.andExpect(jsonPath("$").isEmpty());

is working for me.

Comments

0

This can be tested using an empty map provided with the "jsonpathresultmatchers".

    ResultActions actions = mockMvc.perform(..);
actions.andExpect(jsonPath("$", anEmptyMap()));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.