gpt4 book ai didi

easymock - 如何使用 EasyMock 对传递给 void 方法的参数设置期望

转载 作者:行者123 更新时间:2023-12-02 19:20:50 26 4
gpt4 key购买 nike

我正在使用 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 获得真实的结果

预先感谢您的帮助。

最佳答案

从这个答案中的答案开始: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

关于easymock - 如何使用 EasyMock 对传递给 void 方法的参数设置期望,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10054845/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com