mat*_*t b 91
如果我理解你想要正确做什么,你应该能够使用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;
}
});
Run Code Online (Sandbox Code Playgroud)
在EasyMock的用户指南解释说:
创建返回值或例外
有时我们希望我们的模拟对象返回一个值或抛出在实际调用时创建的异常.由于EasyMock的2.2,则对象返回的
expectLastCall()和expect(T value)提供了方法andAnswer(IAnswer answer),其允许[你]指定接口的实现IAnswer,用于创建的返回值或异常.在
IAnswer回调中,传递给模拟调用的参数可通过EasyMock.getCurrentArguments().如果您使用这些,重新排序参数之类的重构可能会破坏您的测试.你被警告了.
Edw*_*ges 22
如果您只是在每次调用void方法时调用它然后在调用EasyMock.expectLastCall()之前调用replay(),那么Easymock将"记住"每次调用.
所以我认为你不需要显式调用expect()(除了lastCall),因为除了调用之外,你不期望从void方法中得到任何东西.
谢谢克里斯!
StackOverflow用户Burt Beckwith的"Fun With EasyMock"是一篇很好的博客文章,提供了更多细节.值得注意的摘录:
基本上我倾向于使用的流程是:
- 创建一个模拟
- 呼叫
expect(mock.[method call]).andReturn([result])每个预期的电话mock.[method call]然后打电话EasyMock.expectLastCall()给每个预期的无效呼叫- 呼叫
replay(mock)从"录音"模式切换到"播放"模式- 根据需要注入模拟
- 调用测试方法
- 打电话
verify(mock)确保所有预期的电话都发生了
如果您只想稍后访问这些参数,您可能还会欣赏Captures类,它是EasyMock 2.4的新功能.
您可以使用"Capture"类的实例代替匹配器.调用mocked方法时,Capture实例将存储调用它的参数.
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());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
95568 次 |
| 最近记录: |