Arm*_*men 13 java unit-testing easymock
在我的单元测试中,我使用EasyMock来创建模拟对象.在我的测试代码中,我有类似的东西
EasyMock.expect(mockObject.someMethod(anyObject())).andReturn(1.5);
Run Code Online (Sandbox Code Playgroud)
所以,现在EasyMock将接受任何电话someMethod().有没有办法获得传递给它的真正价值mockObject.someMethod(),或者我需要EasyMock.expect()为所有可能的情况编写声明?
hoa*_*oaz 25
您可以使用Captureclass来预期和捕获参数值:
Capture capturedArgument = new Capture();
EasyMock.expect(mockObject.someMethod(EasyMock.capture(capturedArgument)).andReturn(1.5);
Assert.assertEquals(expectedValue, capturedArgument.getValue());
Run Code Online (Sandbox Code Playgroud)
请注意,这Capture是泛型类型,您可以使用参数类对其进行参数化:
Capture<Integer> integerArgument = new Capture<Integer>();
Run Code Online (Sandbox Code Playgroud)
更新:
如果要为expect定义中的不同参数返回不同的值,可以使用andAnswer方法:
EasyMock.expect(mockObject.someMethod(EasyMock.capture(integerArgument)).andAnswer(
new IAnswer<Integer>() {
@Override
public Integer answer() {
return integerArgument.getValue(); // captured value if available at this point
}
}
);
Run Code Online (Sandbox Code Playgroud)
正如评论中所指出的,另一种选择是使用getCurrentArguments()内部调用answer:
EasyMock.expect(mockObject.someMethod(anyObject()).andAnswer(
new IAnswer<Integer>() {
@Override
public Integer answer() {
return (Integer) EasyMock.getCurrentArguments()[0];
}
}
);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16578 次 |
| 最近记录: |