gpt4 book ai didi

java - 如何使用 JUnit 模拟此 webClient?

转载 作者:行者123 更新时间:2023-12-02 09:08:18 25 4
gpt4 key购买 nike

我正在尝试模拟以下方法:

public Mono<PResponse> pay(final String oId,final Double amount) {

return webClient
.put()
.uri("/order/{oId}/amount/{amount}",oId,amount)
.body(BodyInserts
.fromObject(PRequest))
.exchange()
.flatMap(
response -> {
if(response.statusCode().is4xxClientError()) {
// call error Function
} else {
return response
.bodyToMono(PResponse.class)
.flatMap(pResponse -> {
return Mono.just(pResposne)
});
}

}
);
}

供您引用,webClient 是一个私有(private)实例。

最佳答案

您可以使用MockWebServer .这是一个示例,使用此 blog post 中的代码:

服务

class ApiCaller {
private WebClient webClient;

ApiCaller(WebClient webClient) {
this.webClient = webClient;
}

Mono<SimpleResponseDto> callApi() {
return webClient.put()
.uri("/api/resource")
.contentType(MediaType.APPLICATION_JSON)
.header("Authorization", "customAuth")
.syncBody(new SimpleRequestDto())
.retrieve()
.bodyToMono(SimpleResponseDto.class);
}
}

测试

class ApiCallerTest {

private final MockWebServer mockWebServer = new MockWebServer();
private final ApiCaller apiCaller = new ApiCaller(WebClient.create(mockWebServer.url("/").toString()));

@AfterEach
void tearDown() throws IOException {
mockWebServer.shutdown();
}

@Test
void call() throws InterruptedException {
mockWebServer.enqueue(
new MockResponse()
.setResponseCode(200)
.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.setBody("{\"y\": \"value for y\", \"z\": 789}")
);
SimpleResponseDto response = apiCaller.callApi().block();
assertThat(response, is(not(nullValue())));
assertThat(response.getY(), is("value for y"));
assertThat(response.getZ(), is(789));

RecordedRequest recordedRequest = mockWebServer.takeRequest();
//use method provided by MockWebServer to assert the request header
recordedRequest.getHeader("Authorization").equals("customAuth");
DocumentContext context = JsonPath.parse(recordedRequest.getBody().inputStream());
//use JsonPath library to assert the request body
assertThat(context, isJson(allOf(
withJsonPath("$.a", is("value1")),
withJsonPath("$.b", is(123))
)));
}
}

关于java - 如何使用 JUnit 模拟此 webClient?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59623682/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com