【问题标题】:How do I check how many times a mocked method was called?如何检查模拟方法被调用了多少次?
【发布时间】:2016-02-04 19:14:22
【问题描述】:

我有一个已在 @Before 方法中设置的模拟:

  @Before
  public void setup() {
    mockery.checking(new Expectations() {
      {
        allowing(mockExecutor).schedule(with(capture(runnableRef, Runnable.class)), with(0L), with(TimeUnit.MILLISECONDS));
      }
    });
  }

我已经尝试在这个测试用例中添加一个特定的期望(这里只检查 1):

mockery.checking(new Expectations() {
  {
    exactly(1).of(mockExecutor).schedule(with(capture(runnableRef, Runnable.class)), with(0L), with(TimeUnit.MILLISECONDS));
  }
});

但是在结果中我可以看到它从来没有达到这个新的期望,因为它首先达到了“允许”:

java.lang.AssertionError: not all expectations were satisfied
expectations:
  allowed, already invoked 1 time: scheduledExecutorService.schedule(captured value <com.rbsfm.common.db.async.impl.ThrottledExecutor$1@eafc191>, <0L>, 
  expected once, never invoked: scheduledExecutorService.schedule(captured value <com.rbsfm.common.db.async.impl.ThrottledExecutor$1@eafc191>, <0L>, 

在大多数单元测试中,我并不关心schedule 方法被调用的频率(并且它确实因测试而异),但是在一个测试中,我希望检查它是否被准确地调用了 2 次.

有什么方法可以做到这一点,而不必为每个具有不同数字的测试重复模拟配置?

例如,我可以查询Mockery 以了解该方法被调用的频率吗?

【问题讨论】:

    标签: java unit-testing mocking jmock


    【解决方案1】:

    这里讨论了这种情况:http://www.jmock.org/override.html(感谢 Dick Hermann 将我指向该页面)。

    基本思想是您为测试设置一个状态机,并且仅当状态机使用when 处于正确状态时才激活期望。

    public class ChildTest extends TestCase {
        Mockery context = new Mockery();
        States test = context.states("test");
    
        Parent parent = context.mock(Parent.class);
    
        // This is created in setUp
        Child child;
    
        @Override
        public void setUp() {
            context.checking(new Expectations() {{
                ignoring (parent).addChild(child); when(test.isNot("fully-set-up"));
            }});
    
            // Creating the child adds it to the parent
            child = new Child(parent);
    
            test.become("fully-set-up");
        }
    
        public void testRemovesItselfFromOldParentWhenAssignedNewParent() {
            Parent newParent = context.mock(Parent.class, "newParent");
    
            context.checking(new Expectations() {{
                oneOf (parent).removeChild(child);
                oneOf (newParent).addChild(child);
            }});
    
            child.reparent(newParent);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-18
      • 1970-01-01
      • 2017-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多