Search code examples
junitmockitospring-webclient

WebClient GET unit test with mockito


I am facing issue with Webclient and mockito Below is my service code:

public Flux<Config> getConfigs(String param1, String param2) {
        MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<>();

        if(!StringUtils.isEmpty(param2)) {
            queryParams.add("name", param2);
        }
        String path = "api/v1/config";
        return webClient.get().uri(uriBuilder -> uriBuilder.path(path)
                .queryParams(queryParams)
                .build())
                .retrieve().bodyToFlux(Config.class)
                .doOnError(MyRuntimeException::throwError);
    }

Test Case i am trying is failing with below error:

Strict stubbing argument mismatch. Please check:
 - this invocation of 'uri' method:
    requestHeadersUriSpec.uri(
    com.rs.para.conf.service.ConfigServiceImpl$$Lambda$309/1334433160@3925299f
);

Test case code:

@Test
    public void testConfig() {
        List<Config> configs = new ArrayList<>();
        doReturn(requestHeadersUriMock).when(webClientMock).get();
        doReturn(requestHeadersMock).when(requestHeadersUriMock)
                .uri(anyString());
        doReturn(responseMock).when(requestHeadersMock).retrieve();
        doReturn(Flux.fromIterable(configs)).when(responseMock).bodyToFlux(Config.class);
        Flux<Config> configFlux = configService.getConfigs("100005", "test");
    }

I can run normal GET without query param but when I am trying to run this test which has query param it's giving me error PS: I don't want to use mockwebserver


Solution

  • The problem here is you are using a lambda inside the uri method. Whereas in the test cases you are using anyString(). Also since URI has multiple ways of implementation, just using anyString() will not work. Providing a specific class is what is required.

    Changing

    doReturn(requestHeadersMock).when(requestHeadersUriMock)
                    .uri(anyString());
    

    to

     doReturn(requestHeadersMock).when(requestHeadersUriMock).uri(Mockito.any(Function.class));
    

    does the job here.