簡體   English   中英

如何從 Spring WebTestClient JSON 響應中提取值以供后續請求使用?

[英]How to extract values from a Spring WebTestClient JSON response for usage in subsequent requests?

在 Spring Boot 2.4.2 中,我使用WebTestClient在我的集成測試中調用請求。

這是獲取消息列表的第一個請求:

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);

現在我想調用后續請求來下載特定消息。 為此,我需要已經用jsonPath("$[0].id")檢查過的id

webTestClient
    .get()
    .uri(uriBuilder -> uriBuilder.path("/api/messages/{id}").build(extractedId))
    .headers(http -> http.setBearerAuth(token))
    .exchange()
    .expectStatus().isOk();

我怎樣才能把這個id提取到一個局部變量或其他地方,以便它可用於第二個請求?

你可以查看他們的官方文檔

但是稍微擴展一下答案,最簡單的方法就是這樣

val result = webTestClient
                .get()
                .uri(uriBuilder -> uriBuilder.path("/api/messages/{id}").build(extractedId))
                .headers(http -> http.setBearerAuth(token))
                .exchange()
                .expectStatus().isOk()
                .returnResult();

還有一些方法可以獲取文檔中解釋的(無限)響應流,這與上面的示例非常相似。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM