Java 春天JUnit5。网络客户端。如何测试异步调用
我有一个Spring boot项目和一个服务,它基本上调用一个私有方法,它可以:Java 春天JUnit5。网络客户端。如何测试异步调用,java,spring,asynchronous,webclient,junit-jupiter,Java,Spring,Asynchronous,Webclient,Junit Jupiter,我有一个Spring boot项目和一个服务,它基本上调用一个私有方法,它可以: webClient.post().uri().accept(...).body(...).exchange() 然后在上面放置一个subscribe(…),它只记录结果 一切正常,但现在我需要测试一下,这就是事情开始变得有趣的地方 到目前为止,我已经尝试过MockServer、okhttp、Spring的WebMockServer(或其他什么),只有MockServer愿意在某一点上正常工作,而okhttp最新版
webClient.post().uri().accept(...).body(...).exchange()
然后在上面放置一个subscribe(…)
,它只记录结果
一切正常,但现在我需要测试一下,这就是事情开始变得有趣的地方
到目前为止,我已经尝试过MockServer、okhttp、Spring的WebMockServer(或其他什么),只有MockServer愿意在某一点上正常工作,而okhttp最新版本需要junit.rules.*(这对我来说是个问题)
WebMockServer特别需要RestTemplate
Google确实给出了一些例子,其中webClient逻辑方法没有调用.exchange()
,这给了我在测试中调用.block()
的机会,但我不愿意为了解决异步调用而公开私有方法
目前,我正在努力使用Mockito的DEEP_存根策略来模拟实际的webClient链,但这无法从盒子中运行,我试图在编写此问题时使其运行
所以问题是-有没有合适的方法通过异步调用测试webClient(可能是验证超时的MockServer之类的)?Wiremock似乎是一种公认的模拟外部http服务器的方法,现在它是spring测试框架的一部分。 以下是介绍: 否则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);
}
}
Wiremock似乎是一种公认的模拟外部http服务器的方式,它现在是spring测试框架的一部分。 以下是介绍: 否则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);
}
}
你有没有想过,@AppleBuckler?你有没有想过,@AppleBuckler?