WebTestClient使用

2023-11-09

介绍

WebTestClient用于测试WebFlux服务器端点的主要入口点,它具有与WebClient非常相似的API,内部大部分调用WebClient实例,主要提供测试上下文。

  1. 绑定到一个服务
WebTestClient testClient = WebTestClient
  .bindToServer()
  .baseUrl("http://localhost:8080")
  .build();

  1. 绑定路由
RouterFunction function = RouterFunctions.route(
  RequestPredicates.GET("/resource"),
  request -> ServerResponse.ok().build()
);

WebTestClient
  .bindToRouterFunction(function)
  .build().get().uri("/resource")
  .exchange()
  .expectStatus().isOk()
  .expectBody().isEmpty();

  1. 绑定WebHandler
WebHandler handler = exchange -> Mono.empty();
WebTestClient.bindToWebHandler(handler).build();
  1. 绑定一个应用上下文
@Autowired
private ApplicationContext context;

WebTestClient testClient = WebTestClient.bindToApplicationContext(context)
  .build();

  1. 绑定Controller
@Autowired
private Controller controller;

WebTestClient testClient = WebTestClient.bindToController(controller).build();

  1. 生成请求
WebTestClient
  .bindToServer()
    .baseUrl("http://localhost:8080")
    .build()
    .post()
    .uri("/resource")
  .exchange()
    .expectStatus().isCreated()
    .expectHeader().valueEquals("Content-Type", "application/json")
    .expectBody().jsonPath("field").isEqualTo("value");

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

WebTestClient使用 的相关文章

随机推荐