如下所示,我想检查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();
}
}
这是一个旧线程,但我最近遇到了这个问题,并通过使用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();
}
}
}