Difference between @injectMocks and @Autowired usage in mockito?

When I wrote a test case using Mockito and Junit, I used @InjectMocks for the class being tested. In other parts of the project, I also see that @Autowired used for the class being tested.

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

+5
source share
2 answers

@InjectMocks is a Mockito mechanism for entering declared fields in the test class into the corresponding fields in the class during testing . This does not require the test class to be a component of Spring.

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

If you want to use @Autowired annotations in your test class, another approach is to use springockito , which allows you to declare mock beans so that they are automatically added to the test class in the same way that Spring will be an autwire bean. But usually this is not necessary.

+4
source

@InjectMocks annotations tell Mockito to insert all mocks (objects annotated with @Mock annotation) into the fields of the test object. Mockito uses Reflection for this.

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

But I would suggest looking at the benefits of Injection Constructor over Field Injection . In this case, you don’t need to use @InjectMocks , because you can pass mocks to the test object through the constructor. In your test and in production there would be no reflection needed under the hood.

If you want to create an integration test with a subset of Spring beans, I would suggest looking at the @DirtiesContext annotation. It is part of the Spring frame module, commonly called the "Spring Test".

+6
source

Source: https://habr.com/ru/post/1202777/


All Articles