Harsh Kanakhara
Harsh Kanakhara

Reputation: 1153

WebClient ExchangeFilterFunction JUnit

How do I get code coverage for ClientResponseErrorService.genericClientFilter?

  @PostConstruct
  public void init() throws SSLException {
    SslContext sslContext = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE)
        .build();
    HttpClient httpClient = HttpClient.create().secure(sslContextSpec -> sslContextSpec.sslContext(sslContext));
    ClientHttpConnector restConnector = new ReactorClientHttpConnector(httpClient);
    webClient = WebClient.builder()
        .baseUrl(basePath)
        .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
        .defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
        .filter(ClientResponseErrorService.genericClientFilter)
        .clientConnector(restConnector).build();
  }

Here is the ClientResponseErrorService class which I am using inside filter function.

public static ExchangeFilterFunction genericClientFilterFunction() {
    return ExchangeFilterFunction.ofResponseProcessor(clientResponse -> {
      if (clientResponse.statusCode().isError()) {
        clientResponse.bodyToMono(String.class).flatMap(clientResponseBody -> {
          try {
            log.info("Into error Handler");
            return Mono.error(getException(clientResponse, clientResponseBody));
          } catch (Exception ex) {
            return Mono.error(getException(clientResponse, clientResponseBody));

          }
        });
        return Mono.just(clientResponse);
      } else {
        return Mono.just(clientResponse);
      }
    });

  }

I tried this way by creating a MockWebServer

@Test
public void exchangeFilterFunctionTest() throws Exception {
    server.enqueue(new MockResponse().addHeader("Content-Type", "application/json; charset=utf-8")
    .setBody("{}").throttleBody(10000, 3, TimeUnit.MILLISECONDS).setResponseCode(400));
    server.enqueue(new MockResponse().addHeader("Content-Type", "application/json; charset=utf-8")
    .setBody("{}").throttleBody(10000, 3, TimeUnit.MILLISECONDS).setResponseCode(401));
    WebClient webClient = WebClient.builder()
    .baseUrl("http://localhost:"+server.getPort())
    .filter(ClientResponseErrorService.genericClientFilterFunction())
    .build();
    Mono<String> responseMono = webClient.get()
    .uri("http://localhost:"+server.getPort()+"/api")
    .retrieve()
    .bodyToMono(String.class).retry(1);
    StepVerifier.create(responseMono).expectNextCount(1).verifyComplete();
}

but it is giving exception

expectation "expectNextCount(1)" failed (expected: count = 1; actual: counted = 0; signal: onError(org.springframework.web.reactive.function.client.WebClientResponseException$NotFound: 404 Not Found from GET http://localhost:55633/api))
java.lang.AssertionError: expectation "expectNextCount(1)" failed (expected: count = 1; actual: counted = 0; signal: onError(org.springframework.web.reactive.function.client.WebClientResponseException$NotFound: 404 Not Found from GET http://localhost:55633/api))

It is going inside ClientResponseErrorService class but failing at this line clientResponse.bodyToMono(String.class).flatMap(clientResponseBody -> {

Upvotes: 2

Views: 4806

Answers (1)

Michael McFadyen
Michael McFadyen

Reputation: 2987

Here's an example unit test that tests the scenario when the status code is not an error.

@Test
void doNothing_whenStatus200() {
    ClientRequest clientRequest = Mockito.mock(ClientRequest.class);
    ExchangeFunction exchangeFunction = Mockito.mock(ExchangeFunction.class);
    ClientResponse clientResponse = mock(ClientResponse.class);

    given(exchangeFunction.exchange(clientRequest)).willReturn(Mono.just(clientResponse));
    given(clientResponse.statusCode()).willReturn(HttpStatus.OK);

    ExchangeFilterFunction underTest = ClientResponseErrorService.genericClientFilterFunction();

    StepVerifier.create(underTest.filter(clientRequest, exchangeFunction))
            .expectNext(clientResponse)
            .verifyComplete();
}

Upvotes: 2

Related Questions