Testing jsonpath that array contains specfic objects in any order

Marcel Overdijk picture Marcel Overdijk · Oct 21, 2014 · Viewed 11.7k times · Source

I'm testing a Spring controller which can give back a 400 with field errors. These field errors is an array of objects containing a "path" and "message" field.

Now I want to test that some specific call returns multiple errors with specific path and message.

I cannot come to anything closer then below:

.andExpect(jsonPath("$.fieldErrors[*].path", containsInAnyOrder("title", "description")))
.andExpect(jsonPath("$.fieldErrors[*].message", containsInAnyOrder(
    "The maximum length of the description is 500 characters.",
    "The maximum length of the title is 100 characters.")));

But this keeps the option open that bad combinations of "path" and "message" is accepted.

Any ideas how to improve the jsonpath to test this?

Answer

Marcel Overdijk picture Marcel Overdijk · Oct 21, 2014

This seems to the better approach:

.andExpect(jsonPath('$.fieldErrors[?(@.path == \'title\' && @.message == \'The maximum length of the title is 100 characters.\')]').exists())