如何在mock上匹配第二次调用?

时间:2013-06-26 12:29:30

标签: mockito matcher

如下所示,我想检查mock.fireEvent()是否使用特定事件调用(此处为event2)

mock.fireEvent(event1);

mock.fireEvent(event2);

verify(mock).fireEvent(matcherToCheckTheFieldOfEvent2);

但是得到一个错误表明

  verify(mock).fireEvent(matcherToCheckTheFieldOfEvent2);

将尝试匹配首次调用

  mock.fireEvent(argThat(event1));

问题是如何让event2匹配?

Matcher看起来像这样:

    private class IsEvent2 extends ArgumentMatcher<Event2>
    {
      @Override
      public boolean matches(Object arg)
      {
                return ((Event2) arg).methodGotCalled();
      }
    }

1 个答案:

答案 0 :(得分:0)

这是旧线程,但我最近遇到了这个问题并通过使用ArgumentCaptor捕获已触发事件列表并断言列表中存在预期事件来解决它。

ArgumentCaptor<SomeEvent> argument = ArgumentCaptor.forClass(SomeEvent.class);
verify(mock, times(2)).fire(argument.capture());

argument将有一个捕获事件列表,您可以单独断言

assertThat(argument.getAllValues(), hasItems(
    new SomeEventMatcher(event1),
    new SomeEventMatcher(event2)
));

匹配器看起来像这样:

static class SomeEventMatcher extends ArgumentMatcher<SomeEvent> {
    private SomeEvent expected;

    public SomeEventMatcher(SomeEvent expected) {
        this.expected = expected;
    }

    @Override
    public boolean matches(Object argument) {
        if (argument == null) {
            return false;
        }
        else {
            SomeEvent event = (SomeEvent) argument;
            // the fields that you want to compare with the matcher
            return new EqualsBuilder()
                    .append(expected.getField1(), event.getField1())
                    .append(expected.getField2(), event.getField2())
                    .build();
        }
    }
}