【问题标题】:EasyMock: Get real parameter value for EasyMock.anyObject()?EasyMock:获取 EasyMock.anyObject() 的真实参数值?
【发布时间】:2014-01-27 03:37:40
【问题描述】:

在我的单元测试中,我使用 EasyMock 来创建模拟对象。 在我的测试代码中我有这样的东西

EasyMock.expect(mockObject.someMethod(anyObject())).andReturn(1.5);

所以,现在 EasyMock 将接受对 someMethod() 的任何呼叫。有什么方法可以获得传递给mockObject.someMethod() 的真实值,或者我需要为所有可能的情况编写EasyMock.expect() 语句?

【问题讨论】:

  • 你想在哪里获取传递的值?
  • in .andReturn();方法,为不同的情况返回不同的值

标签: java unit-testing easymock


【解决方案1】:

您可以使用Capture 类来获取和捕获参数值:

Capture capturedArgument = new Capture();
EasyMock.expect(mockObject.someMethod(EasyMock.capture(capturedArgument)).andReturn(1.5);

Assert.assertEquals(expectedValue, capturedArgument.getValue());

请注意,Capture 是泛型类型,您可以使用参数类对其进行参数化:

Capture<Integer> integerArgument = new Capture<Integer>();

更新:

如果您想在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
        }
    }
);

正如 cmets 中所指出的,另一种选择是在 answer 内部使用 getCurrentArguments() 调用:

EasyMock.expect(mockObject.someMethod(anyObject()).andAnswer(
    new IAnswer<Integer>() {
        @Override
        public Integer answer() {
            return (Integer) EasyMock.getCurrentArguments()[0];
        }
    }
);

【讨论】:

  • 感谢您的回答。但是不可能在 andReturn 方法中调用 captureArgument.getValue() 对吗? andReturn(capturedArgument.getValue())
  • 我找到了,当我使用 andAnswer insted of andReturn 时,可以使用 captureArgument.getValue() 作为返回值,感谢帮助*
  • 在 andAnswer() 中,您还可以调用 getCurrentArguments() 方法,该方法返回传入的所有参数的 Object[]
  • 您也可以通过myObject.myMethod(capture(captureElement));然后expectLastCall()使用void方法捕获元素
  • 不推荐调用Captureclass 构造函数。请致电EasyMock.newCapture()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-03
  • 1970-01-01
  • 1970-01-01
  • 2017-07-22
  • 2020-04-07
相关资源
最近更新 更多