通过InjectMocks Spy注入一个对象 [英] Injection an object though InjectMocks Spy
问题描述
我需要在一个具有@Autowired Logger实现的类上运行一系列单元测试。实现的基本思想是:
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.
Mockito lib是否允许使用@InjectMock注入对象?我见过@Spy注释的例子,但是当我尝试使用它时,我总是得到NullPointerException。我知道我总是可以直接使用反射,但想法是避免这样的代码。
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.
推荐答案
好吧。如果没有答案,我将不得不自己回答。
Well. I'll have to answer it myself if there's no answers.
要通过@InjectMock注释推送实时对象,使用@Spy注释:
To push a live object through the @InjectMock annotation a @Spy annotation is used:
@Spy
Logger logger = LoggerFactory.getLogger("");
@InjectMocks
TestedClass tested = new TestedClass();
唯一的问题是@Spy无法处理最终(以及其他一些东西)类,其中我在我的案例中打了个招呼。
The only thing is that @Spy cant handle final(and some other things) classes, on which i struck on in my case.
这篇关于通过InjectMocks Spy注入一个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!