问题
I'm trying to mock the return value from a method but I'm getting NotAMockException.
@InjectMocks
private MyService myService;
@Mock
private OtherServiceUsedInMyServiceAsAutowired otherServiceUsedInMyServiceAsAutowired;
Inside MyService I have a method called myMethod() and I want to return dummy object when this method is called.
doReturn(someDummyObject).when(myService).myMethod(any(), any(), any());
And at that point I'm getting the error. What am I doing wrong? Full error:
org.mockito.exceptions.misusing.NotAMockException:
Argument passed to when() is not a mock!
Example of correct stubbing:
doThrow(new RuntimeException()).when(mock).someMethod();
回答1:
The annotation @InjectMocks is used to inject mocks into a tested object:
@InjectMocks- injects mocks into tested object automatically.
It does not mean that object will be a mock itself. This annotation is useful if you want to test an object and want that object to have pre-initialized mock instances automatically (through setter injection).
If you want to create a mock of MyService, use @Mock:
@Mock
private MyService myService;
This will create a mock of MyService and you will need to specify the behaviour you want for that mock. The first thing is that OtherServiceUsedInMyServiceAsAutowired does not make sense anymore: the mocked object won't depend on that class.
来源:https://stackoverflow.com/questions/34613978/org-mockito-exceptions-misusing-notamockexception-on-injectmocks-object