繁体   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