'Unable to mock component that uses RestTemplateBuilder

I have a Springboot application that uses RestTemplate to access a third-party json api. I have written a Component that has the RestTemplate field which is instantiated using Constructor Injection.

  @Service("sample")
  public class SampleService  {
  
  private RestTemplate restTemplate;

  @Autowired
  public SampleService(RestTemplateBuilder builder) {
      this.restTemplate = builder.build();
  }

The service works fine.

I am trying to write test cases for the same.

@RunWith(MockitoJUnitRunner.class)
@SpringBootTest(classes =  {Application.class,ServiceTest.ContextConfiguration.class})
public class ServiceTest {



    @InjectMocks
    @Qualifier("sample")
    SampleService sampleService;


    @Configuration
    static class ContextConfiguration {
        @Bean
        public RestTemplateBuilder restTemplateBuilder() {

            RestTemplateBuilder rtb = mock(RestTemplateBuilder.class);
            RestTemplate restTemplate = mock(RestTemplate.class);

            when(rtb.build()).thenReturn(restTemplate);
            return rtb;
        }
    }
}

I am getting the below exception on test class startup.

org.mockito.exceptions.misusing.InjectMocksException: 
Cannot instantiate @InjectMocks field named 'sampleService' of type 'class com.xxx.xxx.core.SampleService'.
You haven't provided the instance at field declaration so I tried to construct the instance.
However the constructor or the initialization block threw an exception : Cannot invoke "org.springframework.boot.web.client.RestTemplateBuilder.build()" because "builder" is null

How to resolve this?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source