title: Using @InjectMocks to replace @Autowired field with a mocked implementation
body: <p>I want to replace an autowired class of a service in my spring boot app with a mocked implementation of that class that I created specifically for testing.</p>
  
  <p>I chose to create this mocked implementation because the behaviour of this class is too complicated to mock using mockito as it requires multiple other mocks itself.</p>
  
  <p>I am not able to work out how to inject this mocked implementation into the service.</p>
  
  <p>Here is a minimal example of the situation:</p>
  
  <pre><code>@Service
  public class ServiceIWantToTestImpl implements ServiceIWantToTest{
  
      @Autowired
      ComplicatedDependency complicatedDependency;
  
      @Override
      public void methodUsingDependency(){
          String string = complicatedDependency.doSomething();
          System.out.println(string);
      }
  
  }
  
  
  public class MockComplicatedDependency implements ComplicatedDepencency{
  
      public MockComplicatedDependency(...){
          // Inject other mocked objects into this mock
      }
  
      public String doSomthing(){
          // This would be a mocked version of this function for testing
          return "test";
      }
  
  }
  
  @RunWith(MockitoJUnitRunner.class)
  public class TestingTheService(){
      @InjectMock
      private static ServiceIWantToTest serviceIWantToTest = new ServiceIWantToTestImpl();
  
      @Mock
      ComplicatedDependency mockComplicatedDependency;
  
      @BeforeClass
      public static void init(){
          mockComplicatedDependency = new MockComplicatedDependency(...);
      }
  
      @Test
      public void testAttempt(){
          serviceIWantToTest.methodUsingDependency();  // This method calls complicatedDependency.doSomething() which does not run the mocked version in MockComplicatedDependency which I wanted to inject, and would always return null instead of the "test" string I put in this example.
      }
  
  }
  </code></pre>