One way to check that the JSON contains only certain specified keys is to use the jsonPath
method provided by WebTestClient.
Here's an example code snippet that demonstrates this approach:
webTestClient
.get()
.uri("/api/example")
.exchange()
.expectStatus().isOk()
.expectBody()
.jsonPath("$.key1").isNotEmpty() // Check for key1
.jsonPath("$.key2").isNotEmpty() // Check for key2
.jsonPath("$.key3").isEmpty(); // Check that no other keys are present
In this example, we first make a GET request to the /api/example
endpoint using WebTestClient. We then use the expectStatus()
method to ensure that the response status code is 200 OK
, and the expectBody()
method to specify that we want to check the response body.
We use the jsonPath()
method to check each of the keys we're interested in: key1
and key2
. We use the isNotEmpty()
method to check that each key is present and has a non-null value.
Finally, we use the isEmpty()
method to check that no other keys are present in the JSON response. This ensures that the JSON contains only the keys we've specified.
Asked: 2021-08-02 11:00:00 +0000
Seen: 13 times
Last updated: Aug 31 '21