我有一个服务,它调用外部API并映射到实体列表(这是另一个实体)。为了创建单元测试用例,我创建了一个具有所需输出的json文件,并将其映射到那里。
该服务最初使用的是RestTemplate,我可以轻松地用相同的代码来模拟它,但后来我不得不将它更改为WebClient以使其同步,但现在它没有模拟WebClient并导致外部API。
任何帮助都是非常感谢的,我还没有完成整个代码,因为我在WebClient中面临问题--特别是,当我使用RestTemplate时,相同的单元测试已经通过了
我知道MockWebServer会更容易,但如果可能的话,我正在WebClient中寻找解决方案
EntityService.java
public Mono<List<EntityDTO>> getNumber(String Uri) {
return WebClient.builder()
.baseUrl(Uri)
.build()
.get()
.exchange()
.flatMap(response -> response.bodyToMono(EntityDTO.class))
.flatMapMany(dto -> Flux.fromIterable(dto.getEntityDetails()))
.map(this::getEntityDTO)
.collectList();}EntityServiceTest.java
@Test
void shouldReturnEntities() throws IOException {
ServiceInstance si = mock(ServiceInstance.class);
String exampleRequest =new String(Files.readAllBytes(Paths.get("entityPath/entitytest.json")));
ClientResponse response = ClientResponse.create(HttpStatus.OK)
.header(HttpHeaders.CONTENT_TYPE,
MediaType.APPLICATION_JSON_VALUE)
.body(exampleRequest)
.build();
Entity entity = Entity.builder().id("1").name("test")).build
when(si.getServiceId()).thenReturn("external-api");
when(discoveryClient.getInstances(anyString())).thenReturn(List.of(si));
when(webClientBuilder.build().get()).thenReturn(requestHeadersUriSpec);
when(requestHeadersUriSpec.exchange()).thenReturn(Mono.just(response));
when(entityRepository.findById(eq(entity.getId()))).thenReturn(Optional.of(entity));
Flux<EntityDTO> entityNumbers = entityService.getEntityNumbers(entity.getId(),0,1).
StepVerifier.create(entityNumbers).expectNext(entity).verifyComplete();
}发布于 2022-10-24 05:00:19
嘲弄WebClient可能非常棘手,而且容易出错。即使您可以涵盖一些简单的积极情况,也很难测试更复杂的场景,如错误处理、重试、.
我推荐WireMock,它为测试web客户端提供了一个非常好的API。以下是一些例子
stubFor(get("/api")
.willReturn(aResponse()
.withHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE)
.withStatus(200)
.withBody(...)
)
);通过提供不同的存根,您可以很容易地测试正负两种情况。
stubFor(get("/api")
.willReturn(aResponse()
.withHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE)
.withStatus(500)
)
);https://stackoverflow.com/questions/74135867
复制相似问题