Difference between @injectMocks and @Autowired usage in mockito?

Sai Srinadh Kurra picture Sai Srinadh Kurra · Sep 17, 2014 · Viewed 13.2k times · Source

When I was writing test case using the Mockito and Junit, I was using the @InjectMocks for the class to be tested. In other parts of project, I also see @Autowired is being used for the class to be tested.

When can I use @InjectMocks and @Autowired ? What is the difference between two when we are trying to use them with class to be tested ?

Answer

luboskrnac picture luboskrnac · Sep 17, 2014

@InjectMocks annotation tells to Mockito to inject all mocks (objects annotated by @Mock annotation) into fields of testing object. Mockito uses Reflection for this.

@Autowired annotation tells to Spring framework to inject bean from its IoC container. Spring also uses reflection for this when it is private field injection. You can even use even use @Inject annotation (part of Java EE specification) with the same effect.

But I would suggest to look at benefits of Constructor injection over Field injection. In that case you don't need to use @InjectMocks at all, because you can pass mocks into testing object via constructor. There wouldn't be Reflection needed under the hood in your test nor in production.

If you want to create integration test with subset of Spring beans I would suggest to take a look at @DirtiesContext annotation. It is part of Spring framework module commonly called "Spring Test".