4

我正在使用 EasyMock 和 EasyMock CE 3.0 来模拟依赖层并测试我的类。以下是我无法找到任何解决方案的场景

我有要测试的类,它调用一个依赖类void 方法,该方法接受一个输入参数,并更改相同的参数。我正在测试的方法是根据更改的参数进行一些操作,我现在必须针对各种场景进行测试

考虑下面的示例,我尝试在其中放置相同的场景

public boolean voidCalling(){
    boolean status = false;
    SampleMainBean mainBean = new SampleMainBean();
    dependentMain.voidCalled(mainBean);
    if(mainBean.getName() != null){
        status = true; 
    }else{
        status = false;
    }
    return status;
}

和dependentMain 类下面的方法

public void voidCalled(SampleMainBean mainBean){
    mainBean.setName("Sathiesh");
}

为了全面覆盖,我需要有 2 个测试用例来测试返回 true 和 false 的场景,但我总是得到 false,因为我无法设置 void 方法的行为来更改此输入 bean。在这种情况下,如何使用 EasyMock 获得真实的结果

提前感谢您的帮助。

4

2 回答 2

7

从这个答案中的答案开始: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
于 2012-04-11T09:59:05.657 回答
2

感谢您的回复.. 我解决了问题... :) 也感谢您的示例代码。

使用上面的代码片段,我必须做的一个改变是,

// register the expected method
dependentMain.voidCalled((SampleMainBean) EasyMock.anyObject());

有了这个,我就可以在要测试的方法中获取更新的 bean。

再次感谢您的帮助。

于 2012-04-14T10:41:15.657 回答