Add support for strict JSON comparison in WebTestClient

Prior to this commit, WebTestClient only supported "lenient" comparison
of the expected JSON body.

This commit introduces an overloaded variant of `json()` in the
BodyContentSpec that accepts an additional boolean flag to specify
whether a "strict" comparison should be performed.

This new feature is analogous to the existing support in MockMvc.

Closes gh-27993
This commit is contained in:
Gleidson Leopoldo
2022-02-01 09:26:14 +00:00
committed by Sam Brannen
parent a13ad3e969
commit 920be8e1b2
3 changed files with 64 additions and 5 deletions

View File

@@ -659,10 +659,10 @@ class DefaultWebTestClient implements WebTestClient {
}
@Override
public BodyContentSpec json(String json) {
public BodyContentSpec json(String json, boolean strict) {
this.result.assertWithDiagnostics(() -> {
try {
new JsonExpectationsHelper().assertJsonEqual(json, getBodyAsString());
new JsonExpectationsHelper().assertJsonEqual(json, getBodyAsString(), strict);
}
catch (Exception ex) {
throw new AssertionError("JSON parsing error", ex);

View File

@@ -979,7 +979,24 @@ public interface WebTestClient {
* on to be on the classpath.
* @param expectedJson the expected JSON content.
*/
BodyContentSpec json(String expectedJson);
default BodyContentSpec json(String expectedJson) {
return json(expectedJson, false);
}
/**
* Parse the expected and actual response content as JSON and perform a
* comparison in two modes, depending on {@code strict} parameter value, verifying the same attribute-value pairs.
* <ul>
* <li>{@code true}: strict checking.
* <li>{@code false}: lenient checking.
* </ul>
* <p>Use of this option requires the
* <a href="https://jsonassert.skyscreamer.org/">JSONassert</a> library
* on to be on the classpath.
* @param expectedJson the expected JSON content.
* @param strict enables strict checking
*/
BodyContentSpec json(String expectedJson, boolean strict);
/**
* Parse expected and actual response content as XML and assert that