【问题标题】:How to mock this webClient using JUnit?如何使用 JUnit 模拟这个 webClient?
【发布时间】:2020-01-07 07:05:36
【问题描述】:

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

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

【问题讨论】:

  • 尝试添加您迄今为止尝试过的内容,以便我们为您提供帮助
  • 您好,感谢您的回复。我只想模拟这个部分。 return webClient .put() .uri("/order/{oId}/amount/{amount}",oId,amount) .body(BodyInserts .fromObject(PRequest)) .exchange()

标签: java junit mockito call


【解决方案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);
    }
}

测试

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

【讨论】:

    猜你喜欢
    • 2017-12-31
    • 2011-08-30
    • 2021-06-17
    • 1970-01-01
    • 1970-01-01
    • 2021-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多