首页 > 解决方案 > Springboot 测试控制器通过 WebClient 而不是 WebTestClient

问题描述

我正在尝试一些可能被误导的事情,但请帮忙。

我想通过@WebFluxTest. 但是我想使用WebClient而不是WebTestClient. 如何才能做到这一点?

到目前为止,我设法使用反射来ExchangeFunction摆脱 WebTestClient 并将其分配给 WebClient - 它有效!拨打电话,控制器响应 - 太棒了。但是我认为这不是一个好方法。有没有更好的办法?

谢谢你。

标签: springspring-bootunit-testingspring-webclient

解决方案


理想情况下,您应该使用WebTestClient更方便的包装器来围绕WebClient. 就像. TestRestTemplate_ RestTemplate两者都允许创建请求,并且您可以轻松地做出断言。它们的存在是为了让您的测试生活更轻松。

如果您真的想使用 aWebClient而不是 aWebTestClient并手动执行断言(这意味着您可能会使事情复杂化),您可以使用WebClient.Builder创建一个。Spring Boot 会自动配置一个,您可以简单地在测试中自动装配它并调用该build方法。

@SpringBootTest
public void YourTest {
  
  @Autowired
  private WebClient.Builder webClientBuilder;

  @Test
  public void doTest() {
    WebClient webClient = webClientBuilder.build();
  }
}

同样也应该适用@WebFluxTest


推荐阅读