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.
@Spy and @InjectMocks cannot be used well together (see Google Code issue #489 and GitHub issue #169), and for what they do it is not clear or common that they should be used together at all. In well-written Mockito usage, you generally should not even want to apply them to the same object.
@InjectMocks is the Mockito Annotation. It allows you to mark a field on which an injection is to be performed. Injection allows you to, Enable shorthand mock and spy injections.
@Mock is used to declare/mock the references of the dependent beans, while @InjectMocks is used to mock the bean for which test is being created.
Mockito @InjectMocks annotations allow us to inject mocked dependencies in the annotated class mocked object. This is useful when we have external dependencies in the class we want to mock. We can specify the mock objects to be injected using @Mock or @Spy annotations.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With