如果我正确理解你想要做的事情,你应该能够使用andAnswer()
:
mockObject.someMethod(eq(param1), eq(param2));
expectLastCall().andAnswer(new IAnswer() {
public Object answer() {
//supply your mock implementation here...
SomeClass arg1 = (SomeClass) getCurrentArguments()[0];
AnotherClass arg2 = (AnotherClass) getCurrentArguments()[1];
arg1.doSomething(blah);
//return the value to be returned by the method (null for void)
return null;
}
});
EasyMock用户指南解释:
创建返回值或异常
有时我们希望我们的模拟对象返回一个值或抛出在实际调用时创建的异常。自EasyMock 2.2以来,由
expectLastCall()
和expect(T value)
返回的对象提供了方法andAnswer(IAnswer answer)
,它允许您指定接口IAnswer
的实现,用于创建返回值或异常。在
IAnswer
回调中,通过EasyMock.getCurrentArguments()
可用于获取传递给模拟调用的参数。如果您使用这些参数,那么像重新排序参数这样的重构可能会破坏您的测试。您已经被警告了。
如果你每次期望该方法被调用时都只是调用void方法,然后在调用replay()
之前调用EasyMock.expectLastCall()
,EasyMock会“记住”每次调用。
因此,我认为你不需要显式调用expect()
(除了lastCall
),因为你不期望从void方法中获得任何东西,除了它的调用。
感谢Chris!
“Fun With EasyMock”是StackOverflow用户Burt Beckwith的一篇好博客文章,提供了更多详细信息。值得注意的摘录如下:
基本上我倾向于使用以下流程:
- 创建一个mock
- 对于每个预期的调用,调用
expect(mock.[method call]).andReturn([result])
- 对于每个预期的void调用,调用
mock.[method call]
,然后调用EasyMock.expectLastCall()
- 调用
replay(mock)
以从“记录”模式切换到“回放”模式- 按需注入mock
- 调用测试方法
- 调用
verify(mock)
以确保发生了所有预期的调用
Capture<ChartPanel> captured = new Capture<ChartPanel>();
// setChartPanel is going to be called during execution;
// we want to verify some things about the ChartPanel
// instance it's invoked with
chartMock.setChartPanel(capture(captured));
replay(chartMock);
ufdm.setChartAnnotater(chartMock);
// afterPropertiesSet triggers the setChartPanel call...
ufdm.afterPropertiesSet();
verify(chartMock);
// verify some things about the ChartPanel parameter our
// mock object was invoked with
assertSame(plot, captured.getValue().getChart().getPlot());
ClassA
,则应执行以下操作:class MockClassA extends ClassA {
@Override
void specialMethod(String param1, String param2) {
// do logging or manipulation of some sort
super.specialMethod(param1,param2); // if you need to
}
}