Quick revision
The short answer
The tests are fragile because they assume an order the API never promised and because some assertions cannot fail when a path is missing. We fix the first by selecting items by a key with a filter such as $.items[?(@.sku == 'A')].price, or by sorting in the test, and the second by asserting presence explicitly with exists() and doesNotExist() and by not using JsonPath options like SUPPRESS_EXCEPTIONS or DEFAULT_PATH_LEAF_TO_NULL in assertions. For whole responses, one lenient comparison against approved JSON with JSONAssert beats dozens of path checks, and we compare numbers with the type JsonPath actually returns.
What to remember
In this answer, we saw that $.items[0].price checks whatever item is first, so it breaks when an unordered list changes order, and we replaced it with filters on a key, a length check, or sorting in the test. We saw how SUPPRESS_EXCEPTIONS, DEFAULT_PATH_LEAF_TO_NULL and empty wildcard results let missing paths pass, and fixed that with exists(), doesNotExist() and non-empty checks. Finally, we compared whole responses against approved JSON with the right JSONAssert mode and handled number types deliberately.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
The tests are fragile because they assume an order the API never promised and because some assertions cannot fail when a path is missing. We fix the first by selecting items by a key with a filter such as $.items[?(@.sku == 'A')].price, or by sorting in the test, and the second by asserting presence explicitly with exists() and doesNotExist() and by not using JsonPath options like SUPPRESS_EXCEPTIONS or DEFAULT_PATH_LEAF_TO_NULL in assertions. For whole responses, one lenient comparison against approved JSON with JSONAssert beats dozens of path checks, and we compare numbers with the type JsonPath actually returns.
Why this question is asked
Flaky tests are expensive in a quiet way: people start re-running builds instead of reading failures, and soon a real failure is re-run too. Tests that pass when they should fail are worse, because they give confidence that is not there. JSON response tests show both problems often, and interviewers ask this scenario to see whether we know where they come from and how to write assertions that say exactly what the API promises. In this answer, we will recap how jsonPath() assertions work, look at the order problem and fix it, look at why missing paths pass silently, and then cover whole-document comparison and number types.
1A Quick Recap of jsonPath() in MockMvc
MockMvc lets us call a Spring MVC controller in a test without starting a server. After the call, we check the response with result matchers. jsonPath(expression) evaluates a Jayway JsonPath expression against the response body and gives us assertions such as value(), exists(), doesNotExist() and isArray().
An assertion is only as good as the thing it checks. jsonPath("$.items[0].price").value(10.5) does not say 'the item with SKU A costs 10.5'; it says 'whatever item happens to be first costs 10.5'. That difference is the whole first problem.
2Problem 1: The Test Depends on Array Order
The change in the question returns the same items in a different order, perhaps because a repository query lost its ORDER BY, or because the items now come from a HashSet. Unless the API documents an order, both orders are correct, and the test that fails is the one that is wrong. It fails only sometimes because the order depends on data or hashing.
Notice that the filter returns a list, because a filter can match many items. Spring's value() unwraps a list that holds exactly one element before comparing, and fails if it holds none or several, so the assertion still reads naturally; check your Spring version if you rely on that. A Hamcrest matcher such as contains(10.5) makes the list explicit instead. The length check matters too: without it, an extra item would pass unnoticed.
If the API does promise an order, for example 'items sorted by line number', then the order is part of the contract and the test should check it on purpose, with a name that says so. If the order is not promised but we want to compare whole arrays, we can read the array in the test and sort it before comparing.
3Problem 2: Missing Paths That Pass Silently
The second complaint, paths that no longer exist but still pass, usually comes from custom assertions that use JsonPath directly. Jayway's default behaviour is strict: reading a definite path that does not exist throws PathNotFoundException. But two configuration options make missing paths quiet. SUPPRESS_EXCEPTIONS returns null (or an empty list) instead of throwing, and DEFAULT_PATH_LEAF_TO_NULL returns null when the last property is missing. Someone often adds them to stop exceptions in production parsing code, and the same configuration ends up in a test helper.
- Field renamed from delivery to deliveryFeethe API changed
- Read $.fees.deliverypath does not exist
- SUPPRESS_EXCEPTIONS set?Yesreturns null, no errorNoPathNotFoundException, test fails
- Assertion compares null with 5
isNotEqualTopasses
4 steps in order. Play them, or step through them one at a time.
Both assertions pass for the wrong reason. The first compares null with 5, which is never equal. The second checks that every element of an empty list is positive, which is true because there are no elements, a case logicians call vacuously true. Wildcard paths are especially dangerous here, because a missing property gives an empty list rather than an error even without any options.
4Fixing Presence Checks
The fix is to make presence an explicit assertion and to keep test helpers on Jayway's strict default. In MockMvc that means exists() and doesNotExist(), and for lists a non-empty check before any check on the elements.
For an indefinite path, Spring treats an empty result list as not existing, so exists() on $.lines[*].price fails if no line has a price. That makes it a good partner for any element-wise assertion.
5Comparing Whole Responses Instead of Many Paths
When a test checks fifteen paths, it is really trying to describe the whole response, and it will still miss the sixteenth field that appeared by accident. A clearer approach is to compare the body with an approved JSON file. Spring's content().json() uses JSONAssert, and in lenient mode it ignores array order and extra fields, while strict mode checks both. We choose the mode to match the contract.
The approved file also serves as documentation: a reviewer sees exactly what the API returns, and a change to the response shows up as a diff in the pull request.
6Watching Number Types
The last trap is numbers. With the default JSON provider, JsonPath returns 10 as an Integer, 10.5 as a Double and very large values as Long or BigDecimal, depending on the provider and its configuration. An assertion like value(10L) against an Integer 10 can fail although the numbers look equal, and comparing doubles exactly can fail after a calculation. In Spring tests we can use the value() overload that takes a target type, or a matcher such as closeTo(10.5, 0.001); check your Spring version for the exact overloads. Better still, if the field is money, the contract may send it as a string, and then the test compares strings.
7Follow-up questions
Should we ever assert on array order?
Yes, when the API promises it, such as search results sorted by relevance or a paginated list sorted by date. Then the order is behaviour worth testing, and the test name should say so. When the order is not promised, asserting on it makes the test check an accident of the implementation.
Why not just set SUPPRESS_EXCEPTIONS only in production code?
That is the right split. In production parsing, it can be reasonable to treat a missing optional field as null. In tests, we want every missing path to be loud, so test helpers should use Jayway's default configuration or MockMvc's own matchers, never the production configuration.
Are approved JSON files hard to maintain?
Less than many path assertions, if we keep them small and readable. Volatile values such as timestamps and generated ids should be fixed in the test data or excluded with a custom comparator, otherwise every run produces a diff.
8Conclusion
In this answer, we saw that $.items[0].price checks whatever item is first, so it breaks when an unordered list changes order, and we replaced it with filters on a key, a length check, or sorting in the test. We saw how SUPPRESS_EXCEPTIONS, DEFAULT_PATH_LEAF_TO_NULL and empty wildcard results let missing paths pass, and fixed that with exists(), doesNotExist() and non-empty checks. Finally, we compared whole responses against approved JSON with the right JSONAssert mode and handled number types deliberately.
Open with
There are two separate problems. The first is that $.items[0].price checks whatever item is first, and unless the API promises an order, the order can change with the data or with a HashSet, so the test is wrong, not the code.
Then, if they want more
I would select items by a stable key instead, with a filter like items, question mark, at-sign dot sku equals A, then price. A filter returns a list, but Spring's value() unwraps a single-element list, and I would add a length check so an extra item cannot slip through.
If the API does promise an order, I test that on purpose in a test named for it. The second problem is assertions that pass when the path is gone.
That usually happens in custom helpers that use JsonPath with SUPPRESS_EXCEPTIONS or DEFAULT_PATH_LEAF_TO_NULL, so a missing field reads as null and something like isNotEqualTo passes, or with wildcard paths that return an empty list, where an allMatch check is vacuously true.
I would keep test helpers on Jayway's strict default, use exists and doesNotExist explicitly, and check that lists are not empty before checking their elements. For whole responses I prefer comparing with an approved JSON file through content().json or JSONAssert, lenient when array order and extra fields do not matter, stricter when they do.
And I would watch number types, because JsonPath may return Integer, Double or BigDecimal, so I compare with a target type or a tolerance.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Your MockMvc tests use jsonPath("$.items[0].price").value(10.5) and fail intermittently...": https://scrivio-interview-library.netlify.app/java/json-libraries/07361efaac/