0

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

mock.fireEvent(event1);

mock.fireEvent(event2);

verify(mock).fireEvent(matcherToCheckTheFieldOfEvent2);

但是得到一个错误指示

  verify(mock).fireEvent(matcherToCheckTheFieldOfEvent2);

将尝试匹配第一个调用

  mock.fireEvent(argThat(event1));

问题是如何让 event2 匹配?

匹配器看起来像这样:

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

1 回答 1

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();
        }
    }
}
于 2017-07-04T13:09:40.023 回答