Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Injection an object though InjectMocks Spy

Tags:

java

mockito

spy

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.

like image 694
Draaksward Avatar asked Mar 10 '16 21:03

Draaksward


People also ask

Can I use InjectMocks and spy together?

@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.

What does InjectMocks annotation do?

@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.

What is the difference between @mock and @InjectMocks?

@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.

How do you mock injected objects?

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.


1 Answers

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.

like image 140
Draaksward Avatar answered Sep 22 '22 20:09

Draaksward