簡體   English   中英

使用 WebClient 進行 Spring 啟動集成測試

[英]Using WebClient for Spring Boot integration testing

我正在嘗試將 Spring Boot 應用程序的一些集成測試從RestTemplateWebClient 目前,測試使用TestRestTemplate的自動裝配實例

@Autowired
private TestRestTemplate restTemplate;

運行測試時, restTemplate配置為使用與服務器運行相同的基本 URL 和(隨機選擇的)端口。

在我的一項測試中,我登錄並保存授權響應 header 值以供后續 API 調用使用。 我試過像這樣將其遷移到WebClient

WebClient webClient = WebClient.create()

var authResult = webClient.post()
    .uri("/api/authenticate")
    .contentType(MediaType.APPLICATION_JSON)
    .bodyValue(new LoginDetails(username, password))
    .retrieve()
    .toBodilessEntity()
    .block();

// save the token that was issued and use it for subsequent requests
this.authHeader = authResult.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);

但是當我像這樣創建WebClient實例時,它沒有配置為使用與應用程序相同的端口。

我嘗試改為使用TestWebClient的依賴注入實例

@Autowired
private WebTestClient webTestClient;

這確實將 web 客戶端連接到服務器(相同的基礎 URL 和端口),但是WebTestClient API 與WebClient具有完全不同的 API 。 具體來說,它似乎只允許斷言響應的屬性,例如,您可以斷言特定響應 header 值存在,但無法保存該標頭的值。

var authResult = webTestClient.post()
    .uri("/api/authenticate")
    .contentType(MediaType.APPLICATION_JSON)
    .bodyValue(new LoginDetails(username, password))
    .exchange()
    .expectHeader()
    .exists(HttpHeaders.AUTHORIZATION);

有沒有辦法:

  • 創建一個配置為使用與服務器相同的基礎 URL 和端口的WebClient實例
  • 創建一個WebTestClient實例並訪問響應屬性(而不是僅僅斷言它們)

您可以獲得對WebTestClient結果的完全訪問權限:

webTestClient.post()
                .uri("/api/authenticate")
                .contentType(MediaType.APPLICATION_JSON)
                .bodyValue(new LoginDetails(username, password))
                .exchange()
                .expectHeader()
                .exists(HttpHeaders.AUTHORIZATION)
                .returnResult(Map.class);

暫無
暫無

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

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