1

我有一个带有服务的 Spring Boot 项目,它基本上调用了一个私有方法,它执行以下操作:

webClient.post().uri().accept(...).body(...).exchange()

然后在上面放一个subscribe(...),它只是记录结果。

一切正常,但现在我需要对此进行测试,这就是事情开始变得有趣的地方。

到目前为止,我已经尝试过 MockServer、okhttp、Spring 的 WebMockServer(或其他东西),只有 MockServer 愿意在某些时候正常工作,而 okhttp 最新想要 junit.rules.*(实现起来有问题),WebMockServer 特别想要休息模板。

谷歌确实给出了一些例子,其中一个 webClient 逻辑方法没有被.exchange()调用,从而有机会.block()在测试中调用,但我不愿意仅仅为了解决异步调用而公开一个私有方法。

目前,我正在努力使用 Mockito 的 DEEP_STUB 策略来模拟实际的 webClient 链,但这无法从盒子中工作,我试图在编写这个问题时让它工作。

所以问题是 - 有没有合适的方法来测试一个带有异步调用的 webClient (可能是一个 MockServer 验证超时或什么的)?

4

1 回答 1

0

Wiremock 似乎是一种公认​​的模拟外部 http 服务器的方式,它现在是 spring 测试框架的一部分。这是一个介绍:https ://www.baeldung.com/introduction-to-wiremock

否则 WebTestClient 是一个 bean,如果你可以将它注入你的服务类的构造函数中,它可能会派上用场?

@SpringBootTest(webEnvironment = RANDOM_PORT)
@AutoConfigureWebClient
class DemoResourceTest {

    @Autowired
    private WebTestClient webTestClient;

    @BeforeEach
    public void setUp() {
        webTestClient = webTestClient
            .mutate()
            .responseTimeout(Duration.ofMillis(1000))
            .build();
    }

    @Test // just for reference
    void some_test_that_gives_success() {
        webTestClient.get()
            .uri(uriBuilder -> uriBuilder
                .path("/world")
                .queryParam("requestString", "hello")
                .build())
            .accept(APPLICATION_JSON)
            .exchange()
            .expectStatus().isOk()
            .expectBody(String.class);
    }
}
于 2020-10-08T06:16:12.093 回答