问题描述
我有一个 A 类,它使用 3 个不同的类进行自动装配
I have a class A which is using 3 differnt classes with autowiring
public class A () {
@Autowired
private B b;
@Autowired
private C c;
@Autowired
private D d;
}
在测试它们时,我希望只有 2 个类(B 和 C)作为模拟,并且让 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:
@RunWith(MockitoJUnitRunner.class)
public class aTest () {
@InjectMocks
private A a;
@Mock
private B b;
@Mock
private C c;
@Autowired
private D d;
}
有可能这样做吗?
推荐答案
应该是这样的
@RunWith(SpringJUnit4ClassRunner.class)
public class aTest () {
@Mock
private B b;
@Mock
private C c;
@Autowired
@InjectMocks
private A a;
}
如果你想让 D
成为 Autowired
不需要在你的 Test
类中做任何事情.你的 Autowired
A
应该有正确的 D
实例.此外,我认为您需要使用 SpringJUnit4ClassRunner
来使 Autowiring
正常工作,并正确设置 contextConfiguration
.因为你没有使用 MockitoJunitRunner
你需要使用
If you want D
to be Autowired
dont need to do anything in your Test
class. Your Autowired
A
should have correct instance of D
.Also i think you need to use SpringJUnit4ClassRunner
for Autowiring
to work, with contextConfiguration
set correctly.Because you are not using MockitoJunitRunner
you need to initialize your mocks
yourself using
MockitoAnnotations.initMocks(java.lang.Object testClass)
这篇关于如何在 Junit 中使用 @InjectMocks 和 @Autowired 注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!