介绍
WebTestClient用于测试WebFlux服务器端点的主要入口点,它具有与WebClient非常相似的API,内部大部分调用WebClient实例,主要提供测试上下文。
- 绑定到一个服务
WebTestClient testClient = WebTestClient
.bindToServer()
.baseUrl("http://localhost:8080")
.build();
- 绑定路由
RouterFunction function = RouterFunctions.route(
RequestPredicates.GET("/resource"),
request -> ServerResponse.ok().build()
);
WebTestClient
.bindToRouterFunction(function)
.build().get().uri("/resource")
.exchange()
.expectStatus().isOk()
.expectBody().isEmpty();
- 绑定WebHandler
WebHandler handler = exchange -> Mono.empty();
WebTestClient.bindToWebHandler(handler).build();
- 绑定一个应用上下文
@Autowired
private ApplicationContext context;
WebTestClient testClient = WebTestClient.bindToApplicationContext(context)
.build();
- 绑定Controller
@Autowired
private Controller controller;
WebTestClient testClient = WebTestClient.bindToController(controller).build();
- 生成请求
WebTestClient
.bindToServer()
.baseUrl("http://localhost:8080")
.build()
.post()
.uri("/resource")
.exchange()
.expectStatus().isCreated()
.expectHeader().valueEquals("Content-Type", "application/json")
.expectBody().jsonPath("field").isEqualTo("value");