我已经尝试了很多次,@RunWith(SpringJUnit4ClassRunner.class)
我试图用 getter 和 Constructor 注入创建一个测试用例来对抗一个类。当我使用@MockBean
setter注入,构造@Mock
函数注入以及使用bean注入时。如果我评论构造函数注入不起作用。现在所有的 bean 都被完美地注入了,但是beans(Contructor injection ) bean 在调用时模拟了 mthods 不能正常工作。@RunWith(SpringJUnit4ClassRunner.class)
MockitoAnnotations.initMocks(this);
MockitoAnnotations.initMocks(this);
@Mock
@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
}
}
注入工作正常,问题属于我使用的 bean 的模拟方法@Mock
工作不正常意味着mockB.getValue()
重新mockC.getValue()
调整null
但mockA.getValue()
在我测试运行时正确返回。