Ant*_*gos 0 java spring integration-testing spring-boot
我正在尝试将 Spring Boot 应用程序的一些集成测试从 迁移RestTemplate到WebClient. 目前,测试使用自动装配的实例TestRestTemplate
@Autowired
private TestRestTemplate restTemplate;
Run Code Online (Sandbox Code Playgroud)
运行测试时,restTemplate配置为使用与服务器运行相同的基本 URL 和(随机选择的)端口。
在我的一项测试中,我登录并保存授权响应标头值以供后续 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);
Run Code Online (Sandbox Code Playgroud)
但是,当我创建WebClient这样的实例时,它没有配置为使用与应用程序相同的端口。
我尝试使用依赖注入的实例TestWebClient
@Autowired
private WebTestClient webTestClient;
Run Code Online (Sandbox Code Playgroud)
这确实将 Web 客户端连接到服务器(相同的基本 URL 和端口),但是WebTestClientAPI 与WebClient. 具体来说,它似乎只允许断言响应的属性,例如,您可以断言特定的响应标头值存在,但无法保存该标头的值。
var authResult = webTestClient.post()
.uri("/api/authenticate")
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(new LoginDetails(username, password))
.exchange()
.expectHeader()
.exists(HttpHeaders.AUTHORIZATION);
Run Code Online (Sandbox Code Playgroud)
有没有办法:
WebClient配置为使用与服务器相同的基本 URL 和端口的实例WebTestClient实例并访问响应属性(而不仅仅是断言它们)您可以完全访问结果WebTestClient:
webTestClient.post()
.uri("/api/authenticate")
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(new LoginDetails(username, password))
.exchange()
.expectHeader()
.exists(HttpHeaders.AUTHORIZATION)
.returnResult(Map.class);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3642 次 |
| 最近记录: |