我已经尝试了很多次取消唱歌@RunWith(SpringJUnit4ClassRunner.class)
我尝试为带有 getter 和构造函数注入(inject)的类创建一个测试用例。当我使用@MockBean
时用于设定器注入(inject),@Mock
用于构造函数注入(inject),也可以使用 @RunWith(SpringJUnit4ClassRunner.class)
和MockitoAnnotations.initMocks(this);
bean 注入(inject)。
如果我评论MockitoAnnotations.initMocks(this);
构造函数注入(inject)不起作用。
现在所有 bean 都已完美注入(inject),但是 @Mock
beans(构造函数注入(inject))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
}
}
注入(inject)工作正常,问题属于我使用的 bean 的模拟方法 @Mock
无法正常工作意味着mockB.getValue()
和mockC.getValue()
返回null
但是mockA.getValue()
当我测试运行时正确返回。
最佳答案
如果您使用 SpringJUnit4ClassRunner.class
运行测试,则需要使用 @MockBean
而不是 @Mock
。
请引用spring boot documentation
此外,您需要使用@Autowired
而不是@InjectMocks
。
@RunWith(SpringJUnit4ClassRunner.class)
Class TestClass{
@MockBean
A mockA
@MockBean
B mockB
@MockBean
C mockC
@Autowired
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
}
}
关于java - @InjectMocks 通过构造函数和 setter 注入(inject) @MockBean 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58742175/