【问题标题】:EasyMock how to capture argument of a void method called by method under test?EasyMock 如何捕获被测试方法调用的 void 方法的参数?
【发布时间】:2023-04-10 16:15:01
【问题描述】:
【问题讨论】:
标签:
java
mocking
easymock
【解决方案1】:
你只需要调用void方法来记录它。
Capture<String> capturedArgument = new Capture<>();
testObject.voidMethodName(capture(capturedArgument));
replay(testObject);
就是这样。这隐含地意味着您希望 void 方法被调用一次。添加expectLastCall().once(); 或expectLastCall(); 表示完全一样的东西,没有用。
您不能调用expect(),因为 void 方法不会返回任何内容。所以你不能把它作为参数传递给expect()。
您可能想知道为什么 expectLastCall() 会存在。有两个原因:
- 对于像
expectLastCall().andThrow(e)这样的特殊“返回”
- 记录特定数量的呼叫,例如
expectLastCall().atLeastOnce()
【解决方案2】:
TestClass testObj = new TestClass();
Capture<String> capturedArgument = new Capture<>(); //change type as needed
testObj.voidMethodName(capture(capturedArgument));
expectLastCall().atLeastOnce();//adjust number of times as needed
//may need additional replay if you have an additional mocks control object
replay(testObj);
testObj.methodUnderTest();