title: Spring Boot mocking other rest clients when testing
body: <p>I'm consuming a remote api in my Spring MVC project using RestTemplate. One client is for authentication named <code>LoginApiClient</code> and I have to use this in all other rest clients. </p>
  
  <p>This one my rest client that uses <code>LoginApiClient</code> and consumes QrCode Api.</p>
  
  <pre><code>@Service
  public class QrKeyApiClient implements QrKeyApiClientBase {
  
    private RestTemplate restTemplate;
  
    @Autowired
    private LoginApiClientBase loginApiClient;
  
    public QrKeyApiClient(RestTemplateBuilder builder) {
      restTemplate = builder.build();
      restTemplate.setErrorHandler(new ErrorHandler());
    }
  
    //Other implementation details
  }
  </code></pre>
  
  <p>And this is <code>LoginApiClient</code></p>
  
  <pre><code>@Service
  public class LoginApiClient implements LoginApiClientBase {
  
      private RestTemplate restTemplate;
  
      public LoginApiClient(RestTemplateBuilder builder) {
          restTemplate = builder.build();
          restTemplate.setErrorHandler(new ErrorHandler());
      }
  
      //Other implementation details
  }
  </code></pre>
  
  <p>My unit test class for <code>QrKeyApiClient</code> is like below.</p>
  
  <pre><code>@RunWith(SpringRunner.class)
  @RestClientTest({QrKeyApiClient.class})
  @Category(IUnitTest.class)
  public class QrKeyApiClientTest {
  
    @Value("${getQrCodeUrl}")
    private String getQrCodeUrl;
  
    @Mock
    LoginApiClient loginApiClient;
  
    @Autowired
    private MockRestServiceServer server;
  
    @InjectMocks
    private QrKeyApiClient client;
  
    @Test
    public void getQrCodeAsImage_makesTrueCallToApi() throws Exception {
      ResponseEntity&lt;String&gt; responseEntity = mock(ResponseEntity.class);
      HttpEntity requestEntity = new HttpEntity&lt;&gt;(qrCodeGenerateRequest,new HttpHeaders());
  
      this.server
          .expect(requestTo(this.getQrCodeUrl))
          .andExpect(method(HttpMethod.POST))
          .andRespond(withSuccess("successResult", MediaType.TEXT_PLAIN));
  
      String qrImage = this.client.getQrCodeAsImage(qrCodeGenerateRequest);
  
      server.verify();
  
      assertThat(qrImage, is(notNullValue(String.class)));
    }
  }
  </code></pre>
  
  <p>I'm not sure this is the right way to do this but I want to mock my <code>LoginApiClient</code> in this test and inject it to <code>QrKeyApiClient</code>. But my test not passes with an error that says <em>"Error creating bean with name 'qrKeyApiClient': Unsatisfied dependency expressed through field 'loginApiClient';"</em></p>
  
  <p>So how I can test this client with mock of other clients that member of it.</p>