Как смоделировать этот веб-клиент с помощью JUnit? - PullRequest
0 голосов
/ 07 января 2020

Я пытаюсь смутить следующий метод:

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 является частным экземпляром.

1 Ответ

1 голос
/ 07 января 2020

Вы можете использовать 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))
        )));
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...