org.mockito.exceptions.misusing.NotAMockException on InjectMocks object

会有一股神秘感。 提交于 2020-02-03 02:11:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!