Rudziankoŭ
Rudziankoŭ

Reputation: 11251

@InjectMocks and @Spy together give RuntimeException

I have two two methods in the class. I would like to test isolated only one of them.

So I am 'spying' invocation of the second method:

@Spy @InjectMocks private Manager manager;
//...
doReturn(obj).when(manager).method2(any());

I get RuntimeException here:

Caused by: org.mockito.exceptions.base.MockitoException: Cannot create a @Spy for 'manager' field because the *instance* is missing 

What is wrong here?

Upvotes: 0

Views: 5277

Answers (2)

accursed medal 36
accursed medal 36

Reputation: 13

The right way to use would be to use it as

@Spy
List<Integer> list = new ArrayList<>()

Upvotes: -1

vikingjing
vikingjing

Reputation: 21

Firstly, @Spy can be used together with @InjectMocks.

Secondly, I encounter this problem too. when modified @RunWith(PowerMockRunner.class)
to @RunWith(MockitoJUnitRunner.class) , I solved it.

Upvotes: 2

Related Questions