首页 > 解决方案 > 如何使用 JUnit 模拟这个 webClient?

问题描述

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

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 是一个私有实例。

标签: javajunitmockitocall

解决方案


您可以使用MockWebServer。这是一个示例,使用此博客文章中的代码:

服务

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))
        )));
    }
}

推荐阅读