EasyMock.andVoid() 的目的是什么?

What is the purpose of EasyMock.andVoid()?

EasyMock.andVoid() 的 javadoc 如下所示

Records a call but returns nothing. Used to chain calls on void methods expectLastCall().andThrow(e).andVoid()

Returns:

this object to allow method call chaining.lockquote

你知道任何可能需要这个的情况吗?上面的例子中andVoid()的目的是什么?

让我们考虑一下:

myMock.myMethod();
expectLastCall().andVoid().andThrow(e)

myMethod 有 return 类型 void。然后我们可以省略 'chain-element' andVoid.

related API docs 是这样的:

Records a call but returns nothing. Used to chain calls on void methods expectLastCall().andThrow(e).andVoid()

重点是给通话录音。稍后 verify 调用可以检查此调用是否发生。

你真的很少需要这个。因为大多数情况下你只需要调用 void 方法来模拟它。像这样

MyClass myMock = mock(MyClass.class);
myMock.myMethod();
replay(myMock);
myMock.myMethod(); // one call to myMethod expected
verify(myMock);

这是

的同义词
MyClass myMock = mock(MyClass.class);
myMock.myMethod();
expectLastCall();
replay(myMock);
myMock.myMethod(); // one call to myMethod expected
verify(myMock);

然后假设您希望第一次调用 myMethod 抛出异常,第二次正常响应,您可以这样做。

MyClass myMock = mock(MyClass.class);
myMock.myMethod();
expectLastCall().andThrow(new RuntimeException("test"));
expectLastCall().andVoid();
replay(myMock);
try {
  myMock.myMethod(); // one call to myMethod will throw an exception
  fail("should throw");
} catch(RuntimeException e) {}
myMock.myMethod(); // the other will be normal
verify(myMock);

或者通过链接它们

MyClass myMock = mock(MyClass.class);
myMock.myMethod();
expectLastCall().andThrow(new RuntimeException("test")).andVoid();
replay(myMock);
try {
  myMock.myMethod(); // one call to myMethod will throw an exception
  fail("should throw");
} catch(RuntimeException e) {}
myMock.myMethod(); // the other will be normal
verify(myMock);

这种用例当然非常少见,但我们仍然支持它。