我使用EasyMock和EasyMock CE 3.0来模拟依赖层并测试我的类.以下是我无法找到任何解决方案的情况
我有要测试的类,它调用一个依赖类的void方法,它接受一个输入参数,并改变相同的参数.我正在测试的方法是基于改变的param做一些操作,我现在必须针对各种场景进行测试
考虑下面的示例,我试图将相同的场景放在一起
public boolean voidCalling(){
boolean status = false;
SampleMainBean mainBean = new SampleMainBean();
dependentMain.voidCalled(mainBean);
if(mainBean.getName() != null){
status = true;
}else{
status = false;
}
return status;
}
Run Code Online (Sandbox Code Playgroud)
而dependentMain类则采用以下方法
public void voidCalled(SampleMainBean mainBean){
mainBean.setName("Sathiesh");
}
Run Code Online (Sandbox Code Playgroud)
为了完全覆盖,我需要有两个测试用例来测试返回true和false的场景,但是我总是得到假,因为我无法设置void方法的行为来改变这个输入bean.如何使用EasyMock在此场景中获得真实结果
在此先感谢您的帮助.
从这个答案的答案开始:EasyMock:Void Methods,你可以使用IAnswer.
// create the mock object
DependentMain dependentMain = EasyMock.createMock(DependentMain.class);
// register the expected method
dependentMain.voidCalled(mainBean);
// register the expectation settings: this will set the name
// on the SampleMainBean instance passed to voidCalled
EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {
@Override
public Object answer() throws Throwable {
((SampleMainBean) EasyMock.getCurrentArguments()[0])
.setName("Sathiesh");
return null; // required to be null for a void method
}
});
// rest of test here
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5788 次 |
| 最近记录: |