Ask Your Question
1

How can I check in WebTestClient that the JSON contains only certain specified keys?

asked 2021-08-02 11:00:00 +0000

woof gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2021-08-31 05:00:00 +0000

djk gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-08-02 11:00:00 +0000

Seen: 10 times

Last updated: Aug 31 '21