如何使用JUnit模拟此webClient?

问题描述 投票:0回答:1

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

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

java junit mockito call
1个回答
1
投票

您可以使用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);
    }
}

Test

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))
        )));
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.