@Autowire combined with @InjectMocks

I have a Spring boot project that has a set of unit tests that use mockito @InjectMocks in order to both instantiate the tested class and introduce any layouts that may be present in it.

In other words, if I have this

@InjectMocks MyClass myClass;

Then i don't need

MyClass myclass = New MyClass ();
or @Autowired MyClass myClass;

So far, this setting has worked fine.

However, recently it has become necessary to have access to Spring boot properties when running tests. This means that you had to use the run-run SpringBoot inside the tests in order for all @Autowire instances to work (including those that instantiate the Environment class).

, @InjectMocks , @Autowired (, , ). Spring.

@Autowired @InjectMocks

@InjectMocks MyClass myClass;

@Autowired
@InjectMocks MyClass myClass;

. - ? myClass ,

+4
1

, , spring, , Mockito.

- @Autowired . , new. spring. mockito .

, . spring , mockito, . @InjectMocks mockito: ", @Mock, , , ". , @Autowired . Mockito spring.

: , @Autowired @InjectMocks . spring mockito .

, , . , , .

+4

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


All Articles