EasyMock捕获:在IAnswer之外使用getValue()

时间:2012-12-20 17:22:10

标签: java unit-testing mocking capture easymock

假设我想使用 EasyMock 测试方法Foo.doSomething(String arg):String。我知道我可以使用 EasyMock Capture 来捕获参数内的值集,然后在以后获取它。在编写测试时,我的目标是在模拟Foo的方法时捕获值,然后在我的模拟方法之外获取捕获的值。我正在尝试这样的事情:

Capture<String> stringCapture = new Capture<String>();
EasyMock.expect(foo.doSomething(EasyMock.capture(stringCapture)).andAnswer(new IAnswer<String> {
    @Override
    public String answer() throws Throwable {
        ...
});
String retrievedValue = stringCapture.getValue();

但是,当我尝试使用getValue()时,我收到运行时错误:

java.lang.AssertionError: Nothing captured yet
    at org.easymock.Capture.getValue(Capture.java:80)
    at com.example.Test.myTest(...)
    ....

我希望我的测试方法中有一个String变量,但在IAsnwer闭包之外,并在我的IAnswer.answer()方法中设置该变量的值。问题是String变量必须标记为final才能被闭包访问,这使得它不可修改,因此无用。此外,我不希望使用全球公正来解决这个问题。

我认为使用我自己的具有String字段的类的唯一解决方法是将其声明为final之外的IAnswer变量,在answer()期间设置捕获的值最后将此值设置为我的测试方法中的一个字段。也许还有更好的方法,因为使用另一个类来提取捕获的值,甚至是全局变量,对我来说似乎很难看。

1 个答案:

答案 0 :(得分:2)

getValue只能在对foo的实际(重放)调用之后才能工作。在此之前,没有什么是捕获。

要在answer()中设置变量,因为Java请求内部类中使用的变量是最终的,我通常使用AtomicReference。这是一个很好的占位符。 AtomicReference是最终的,但其内容不是。