javaspringspring-boot-2

Mockito "when" method does not match lambda argument on RestTemplateBuilder requestFactory in spring boot 2


I am having an issue when trying to mock restTemplateBuilder:

private RestTemplate restTemplate() {

    HttpClient client = HttpClients.custom().build();


    return restTemplateBuilder.
           requestFactory(() -> new HttpComponentsClientHttpRequestFactory(client)).
           build();
}

My test method setup below:

    @Before
    public void setUp() {
        when(restTemplateBuilder.requestFactory(() -> any(ClientHttpRequestFactory.class))).thenReturn(restTemplateBuilder);
        when(restTemplateBuilder.build()).thenReturn(restTemplate);
    }

In this case, requestFactory always returns null. Mockito also gives me a hint that first line in setup is not in use, and ask on the line with requestFactory if "args ok?".


Solution

  • You need a matcher for the lambda function in your when clause. You can use argThat from Mockito like:

    when(restTemplateBuilder.requestFactory(argThat(()-> new HttpComponentsClientHttpRequestFactory(clientMock))).thenReturn(restTemplateBuilder);
    

    Having client as a mock.


    Another way to do it could be using ArgumentCaptor:

        @Captor
        private ArgumentCaptor<Supplier> lambdaCaptor;
    

    and using it:

    when(restTemplateBuilder.requestFactory(lambdaCaptor.capture()).thenReturn(restTemplateBuilder);
    

    If you need more info about matching lambdas check the documentation.