title: Injecting a mock into a spied object of the same type
body: <p>My object under test implements an interface, and has a field whose type is this same interface (a delegate). I want both a Mock object that I can inject into the <code>delegate</code> field of the object under test, and I want the object under test to be a Spy (not really relevant in this example, but in my situation I want to be able to stub some of the object's methods).</p>
  
  <pre><code>import static org.mockito.Mockito.*;
  
  import org.junit.Test;
  import org.junit.runner.RunWith;
  import org.mockito.*;
  import org.mockito.runners.MockitoJUnitRunner;
  
  @RunWith(MockitoJUnitRunner.class)
  public class UselessTest {
  
    @Mock private Useless mock;
  
    @Spy private UnderTest underTest = new UnderTest() {};
  
    @Before public void before() { underTest.delegate = mock; }
  
    @Test public void testDoNothing() throws Exception {
      underTest.doNothing();
      verify(mock).doNothing();
    }
  
    public interface Useless { void doNothing(); }
  
    public abstract static class UnderTest implements Useless {
      public Useless delegate;
      @Override public void doNothing() { delegate.doNothing(); }
    }
  
  }
  </code></pre>
  
  <p>I'd like to use the <code>@InjectMocks</code> annotation instead of the <code>@Before</code> initialization method, but I haven't been successful so far.</p>
  
  <p>I'm using Mockito 1.9.5 and JUnit 4.11.</p>
  
  <p>I have tried several solutions, each one failing for a different reason. :</p>
  
  <pre><code>@Spy @InjectMocks private UnderTest underTest;
  
  @Spy @InjectMocks private UnderTest underTest = new UnderTest() {};
  
  @InjectMocks private UnderTest underTest = Mockito.spy(new UnderTest() {});
  </code></pre>
  
  <p>With the first solution, the test ends up in error with the exception <code>org.mockito.exceptions.base.MockitoException</code> (the abstract class <code>UnderTest</code> cannot be instantiated by Mockito)</p>
  
  <p>With the second solution, the test ends up in error with the exception <code>org.mockito.exceptions.misusing.NotAMockException</code> (Mockito tried to inject the object under test into itself instead of the mock with the same interface)</p>
  
  <p>And finally with the third solution, the test ends up in error with the exception <code>java.lang.NullPointerException</code> while calling the test method (Mockito did not inject the mock into the <code>delegate</code> field)</p>