Mockito Inject mock into Spy object

I’ve also wandered how to inject a mock into a spy.

The following approach will not work:

@Spy
@InjectMocks
private MySpy spy;

But the desired behavior can be achieved by a “hybrid” approach, when using both annotation and manual mocking. The following works perfectly:

@Mock
private NeedToBeMocked needToBeMocked;

@InjectMocks
private MySpy mySpy;

@InjectMocks
private SubjectUnderTest sut;

@BeforeMethod
public void setUp() {
    mySpy = Mockito.spy(new MySpy());
    MockitoAnnotations.initMocks(this);
}

(SubjectUnderTest here depends on MySpy, and MySpy in its turn depends on NeedToBeMocked).

UPD: Personally, I think that if you have to do such a magic too often, it might be a sign that there is something wrong with dependenicies between your classes and it is worth to perform a little bit of refactoring to improve your code.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)