Search code examples
javaspringdependency-injectionmockitospring-ioc

Difference between @InjectMocks and @Autowired usage in mockito?


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?


Solution

  • @InjectMocks is a Mockito mechanism for injecting declared fields in the test class into matching fields in the class under test. It doesn't require the class under test to be a Spring component.

    @Autowired is Spring's annotation for autowiring a bean into a production, non-test class.

    If you wanted to leverage the @Autowired annotations in the class under test, another approach would be to use springockito which allows you to declare mock beans so that they will be autowired into the class under test the same way that Spring would autowire the bean. But typically that's not necessary.