【问题标题】:EasyMock how to capture argument of a void method called by method under test?EasyMock 如何捕获被测试方法调用的 void 方法的参数?
【发布时间】:2023-04-10 16:15:01
【问题描述】:

从文档中,我的理解是,expectLastCall() 将用于 void 方法,而不是 expect(),因此我在 Eclipse 中这样做时会收到投诉。

Capture<String> capturedArgument = new Capture<>();
expect(testObject.voidMethodName(capture(capturedArgument)));

这个How to expect void method call with any argument using EasyMock 不起作用。

【问题讨论】:

    标签: java mocking easymock


    【解决方案1】:

    你只需要调用void方法来记录它。

    Capture<String> capturedArgument = new Capture<>();
    testObject.voidMethodName(capture(capturedArgument));
    replay(testObject);
    

    就是这样。这隐含地意味着您希望 void 方法被调用一次。添加expectLastCall().once();expectLastCall(); 表示完全一样的东西,没有用。

    您不能调用expect(),因为 void 方法不会返回任何内容。所以你不能把它作为参数传递给expect()

    您可能想知道为什么 expectLastCall() 会存在。有两个原因:

    1. 对于像expectLastCall().andThrow(e)这样的特殊“返回”
    2. 记录特定数量的呼叫,例如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();
      

      【讨论】:

      • 你为什么需要一个部分模拟?!?
      猜你喜欢
      • 1970-01-01
      • 2012-07-27
      • 2011-04-12
      • 1970-01-01
      • 1970-01-01
      • 2013-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多