Difference between @injectMocks and @Autowired usage in mockito?

我是研究僧i 提交于 2019-11-30 13:43:51

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!