Java 如何在 Junit 中使用 @InjectMocks 和 @Autowired 注释
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34067956/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use @InjectMocks along with @Autowired annotation in Junit
提问by USer22999299
I have a class A which is using 3 differnt classes with autowiring
我有一个 A 类,它使用 3 个不同的类进行自动装配
public class A () {
@Autowired
private B b;
@Autowired
private C c;
@Autowired
private D d;
}
While testing them, i would like to have only 2 of the classes (B & C) as mocks and have class D to be Autowired as normal running, this code is not working for me:
在测试它们时,我只想将 2 个类(B 和 C)作为模拟,并让 D 类在正常运行时自动装配,此代码对我不起作用:
@RunWith(MockitoJUnitRunner.class)
public class aTest () {
@InjectMocks
private A a;
@Mock
private B b;
@Mock
private C c;
@Autowired
private D d;
}
Is it even possible to do so?
甚至有可能这样做吗?
采纳答案by Sajan Chandran
It should be something like
它应该是这样的
@RunWith(SpringJUnit4ClassRunner.class)
public class aTest () {
@Mock
private B b;
@Mock
private C c;
@Autowired
@InjectMocks
private A a;
}
If you want Dto be Autowireddont need to do anything in your Testclass. Your AutowiredAshould have correct instance of D.
Also i think you need to use SpringJUnit4ClassRunnerfor Autowiringto work, with contextConfigurationset correctly.
Because you are not using MockitoJunitRunneryou need to initialize your mocksyourself using
如果你想D成为Autowired不需要在你的Test课堂上做任何事情。你AutowiredA应该有正确的D. 此外,我认为您需要使用SpringJUnit4ClassRunnerforAutowiring工作,并contextConfiguration正确设置。因为您没有使用,所以MockitoJunitRunner您需要mocks使用
MockitoAnnotations.initMocks(java.lang.Object testClass)
MockitoAnnotations.initMocks(java.lang.Object testClass)
回答by Thomas
I was facing same problem and tried the answer by Sajan Chandran. It didn't work in my case because I'm using @SpringBootTest annotation to load only a subset of all my beans. The goal is not to load the beans that I'm mocking since they have lot of other dependencies and configurations.
我遇到了同样的问题,并尝试了 Sajan Chandran 的答案。它在我的情况下不起作用,因为我使用 @SpringBootTest 注释只加载我所有 bean 的一个子集。目标不是加载我正在模拟的 bean,因为它们有很多其他依赖项和配置。
And I found the following variant of the solution to work for me, which is usable in normal case also.
我发现以下解决方案变体对我有用,在正常情况下也可以使用。
@RunWith(SpringRunner.class)
@SpringBootTest(classes={...classesRequired...})
public class aTest () {
@Mock
private B b;
@Mock
private C c;
@Autowired
@Spy
private D d;
@InjectMocks
private A a;
@Before
public void init(){
MockitoAnnotations.initMocks(this);
}
}

