Mockito UnfinishedStubbingException in LamdaFunction

Viewed 290

I am trying to mock

this.restTemplate =
restTemplateBuilder
    .messageConverters(converter)
    .requestFactory(() -> new HttpComponentsClientHttpRequestFactory(httpClient))
    .build();

I am using following code

doReturn(restTemplateBuilder).when(restTemplateBuilder).messageConverters(any(MappingJackson2HttpMessageConverter.class);
doReturn(restTemplateBuilder).when(restTemplateBuilder).requestFactory(lambdaCaptor.capture());
doReturn(restTemplate).when(restTemplateBuilder).build();

The requestFactory part is giving error

org.mockito.exceptions.misusing.UnfinishedStubbingException: 
Unfinished stubbing detected here:
1 Answers

The error

ERROR - org.mockito.exceptions.misusing.UnfinishedStubbingException: Unfinished stubbing detected here

happens because some of these cases:

  1. missing thenReturn()
  2. you are trying to stub a final method, you naughty developer!
  3. you are stubbing the behaviour of another mock inside before 'thenReturn' instruction if completed

I think that your example is close to the third item. You cannot use captor object -> lambdaCaptor.capture() inside a Mockito.when().

Basically, you need to find a way to mock HttpComponentsClientHttpRequestFactory. There might be multiple ways to do it. I would start looking at how to mock the interface that it implements: ClientHttpRequestFactory. Here on the official source code there are some examples. This answer also looks very close to what you need.

Related