EasyMock:无效方法

Ike*_*nez 68 java unit-testing easymock mocking void

我有一个方法在类中返回void,该类是我想要测试的类的依赖项.

这个类非常庞大,我只使用这个单一的方法.我需要替换此方法的实现以进行测试,因为我希望它能够执行不同的操作,并且我需要能够访问此方法接收的参数.

我无法在EasyMock中找到这样做的方法.我想我知道如何通过使用Mockito来做到这一点,doAnswer但除非绝对必要,否则我不想添加另一个库.

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"是一篇很好的博客文章,提供了更多细节.值得注意的摘录:

基本上我倾向于使用的流程是:

  1. 创建一个模拟
  2. 呼叫expect(mock.[method call]).andReturn([result])每个预期的电话
  3. mock.[method call]然后打电话EasyMock.expectLastCall()给每个预期的无效呼叫
  4. 呼叫replay(mock)从"录音"模式切换到"播放"模式
  5. 根据需要注入模拟
  6. 调用测试方法
  7. 打电话verify(mock)确保所有预期的电话都发生了


pie*_*era 5

如果您只想稍后访问这些参数,您可能还会欣赏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)