With Spring Boot 2.4.2 I'm using the WebTestClient
to invoke requests in my integration tests.
This is the first request which gets a list of messages:
webTestClient
.get()
.uri("/api/messages")
.headers(http -> http.setBearerAuth(token))
.exchange()
.expectStatus().isOk()
.expectHeader().contentType(APPLICATION_JSON)
.expectBody()
.jsonPath("$.length()").isEqualTo(1)
.jsonPath("$[0].id").isNumber()
.jsonPath("$[0].type").isEqualTo(4);
Now I'd like to invoke a subsequent request to download a specific message. For this, I need the id
which was already checked with jsonPath("$[0].id")
.
webTestClient
.get()
.uri(uriBuilder -> uriBuilder.path("/api/messages/{id}").build(extractedId))
.headers(http -> http.setBearerAuth(token))
.exchange()
.expectStatus().isOk();
How can I extract this id
into a local variable or else, so that it's available for the second request?
I encountered the same problem, and this is the solution I came up with.
According to documentation,
To my understanding it is geared for testing the response in a similar fashion as
assertThat
assertations do.In my solution I instead use
WebClient
for extracting values.The code snippet below should explain all the details. Note that it is just a generalized example, you should tailor it for your needs.
Edit: After some further tries, I found a way to extract the response with WebTestClient too: