1

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?".

Damian229
  • 482
  • 5
  • 10
Dariusz Urbanek
  • 166
  • 1
  • 11

1 Answers1

0

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.

Damian229
  • 482
  • 5
  • 10
  • So the first option does not work for me, having error that "Cannot resolve method 'requestFactory(T)'". Second one works with @Captor private ArgumentCaptor lambdaCaptor; – Dariusz Urbanek Jul 03 '20 at 11:20