Java EasyMock:获取 EasyMock.anyObject() 的真实参数值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21005775/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
EasyMock: Get real parameter value for EasyMock.anyObject()?
提问by Armen
In my unit tests I'm using EasyMock for creating mock objects. In my test code I have something like this
在我的单元测试中,我使用 EasyMock 来创建模拟对象。在我的测试代码中,我有这样的事情
EasyMock.expect(mockObject.someMethod(anyObject())).andReturn(1.5);
So, now EasyMock will accept any call to someMethod()
. Is there any way to get real value that is passed to mockObject.someMethod()
, or I need to write EasyMock.expect()
statement for all possible cases?
所以,现在 EasyMock 将接受任何对someMethod()
. 有没有办法获得传递给 的真实值mockObject.someMethod()
,或者我需要EasyMock.expect()
为所有可能的情况编写语句?
采纳答案by hoaz
You can use Capture
class to expect and capture parameter value:
您可以使用Capture
类来期望和捕获参数值:
Capture capturedArgument = new Capture();
EasyMock.expect(mockObject.someMethod(EasyMock.capture(capturedArgument)).andReturn(1.5);
Assert.assertEquals(expectedValue, capturedArgument.getValue());
Note that Capture
is generic type and you can parametrize it with an argument class:
请注意,这Capture
是泛型类型,您可以使用参数类对其进行参数化:
Capture<Integer> integerArgument = new Capture<Integer>();
Update:
更新:
If you want to return different values for different arguments in your expect
definition, you can use andAnswer
method:
如果要为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
}
}
);
As pointed in comments, another option is to use getCurrentArguments()
call inside answer
:
正如评论中所指出的,另一种选择是使用getCurrentArguments()
call inside answer
:
EasyMock.expect(mockObject.someMethod(anyObject()).andAnswer(
new IAnswer<Integer>() {
@Override
public Integer answer() {
return (Integer) EasyMock.getCurrentArguments()[0];
}
}
);