Injection an object though InjectMocks Spy

纵然是瞬间 提交于 2019-12-07 06:33:29

问题


I need to run series of unit tests over a class, which has a @Autowired Logger implementation. The base idea of realization was:

@Mock Logger logger;
@InjectMocks
TestedClass tested;

but i want to save the logging output functionality.

Does Mockito lib allow to inject objects with @InjectMock? I'w seen examples of @Spy annotation, but when i tried to use it, i always got NullPointerException. I know that i can always directly use reflect, but the idea is to avoid such code.


回答1:


Well. I'll have to answer it myself if there's no answers.

To push a live object through the @InjectMock annotation a @Spy annotation is used:

@Spy
Logger logger = LoggerFactory.getLogger("");
@InjectMocks
TestedClass tested = new TestedClass();

The only thing is that @Spy cant handle final(and some other things) classes, on which i struck on in my case.



来源:https://stackoverflow.com/questions/35927930/injection-an-object-though-injectmocks-spy

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