@@ InjectMocks通过构造方法和设置方法注入@MockBean不能正常工作

问题描述 投票:0回答:1

我通过取消@RunWith(SpringJUnit4ClassRunner.class)尝试了很多次我试图用getter和Constructor注入创建一个测试用例。当我将@MockBean用于setter注入时,将@Mock用于构造函数注入,并且还使用@RunWith(SpringJUnit4ClassRunner.class)MockitoAnnotations.initMocks(this); bean注入。如果我评论MockitoAnnotations.initMocks(this);构造函数注入无效。现在所有的bean都被完美地注入了,但是@Mock bean(注入了Contructor)bean嘲笑了它们在调用时无法正常工作。

@Component
Class A{
}

@Component
Class B {
}

@Component
Class c{
}

@Component
Class D{
@Atowired
A a;

B b;
C c;
@Autowired
public D(B b,C c){
b=b;
c=c;
}
}

我的测试班是

@RunWith(SpringJUnit4ClassRunner.class)
Class TestClass{
@MockBean
A mockA
@Mock
B mockB
@Mock
C mockC
@InjectMocks
D mockD

@Before
public void setUp() {
MockitoAnnotations.initMocks(this);//Without this Constructor injection not working
when(mockA.getValue()).then("StringValA");
when(mockB.getValue()).then("StringValB");
when(mockC.getValue()).then("StringValC");

}
@Test
public void testMethod(){
mock.getAllValues();// It will call all injested bean method we are mocked in @before 
}
}

我通过取消使用@RunWith(SpringJUnit4ClassRunner.class)尝试了很多次,我试图用getter和Constructor注入创建一个针对一个类的测试用例。当我使用@MockBean作为设置程序时...

java dependency-injection mockito junit4 springmockito
1个回答
0
投票

当您使用springRunner运行测试时,必须指定要作为bean加载的确切内容(阅读,让spring知道应在应用程序上下文中确切包含什么)。

© www.soinside.com 2019 - 2024. All rights reserved.