Mockito Verify 方法没有给出一致的结果

Mockito Verify method not giving consistent results

我正在学习 GwtMockito,但在我的一项测试中无法获得一致的 verify() 方法结果。

我正在尝试测试我的应用程序是否触发了正确的 GwtEvents。所以我在我的@Before 方法中像这样模拟了事件总线:

eventBus = mock(HandlerManager.class);

此测试按预期通过:

// Passes as expected
verify(eventBus).fireEvent(any(ErrorOccurredEvent.class));

我想强制测试失败只是为了知道它 运行 正确。所以我把它改成了这个,它仍然通过:

// Expected this to fail, but it passes
verify(eventBus).fireEvent(any(ErrorOccurredEvent.class));
verifyZeroInteractions(eventBus).fireEvent(any(ErrorOccurredEvent.class));

这对我来说似乎是矛盾的。所以我删除了第一个测试:

// Fails as expected
verifyZeroInteractions(eventBus).fireEvent(any(ErrorOccurredEvent.class));

最后我添加了一个应该导致它失败的无关事件

// Expected to fail, but passes
verify(eventBus).fireEvent(any(ErrorOccurredEvent.class));
verify(eventBus).fireEvent(any(ModelCreatedEvent.class));  // This event is not used at all by the class that I'm testing. It's not possible for it to be fired.

我找不到任何说明发生了什么的文档。 ErrorOccurredEvent 和 ModelCreatedEvent 都扩展了 GwtEvent,并且已经在手动测试中得到验证。我是否错误地测试了我的 EventBus?如果是这样,有什么更好的方法吗?

更新

我做了一些额外的实验。这似乎是我在使用 Mockito 匹配器时遇到的问题。当我的测试失败时,异常将方法签名报告为 eventBus.fireEvent(<any>),因此它似乎没有考虑到我传递给 any 方法的不同 类。尚不确定如何处理此问题,但将其包含在此处以供研究此问题的其他人使用。

这并不能解释我第一次强制测试失败的尝试,但它确实解释了其他混淆。来自 Mockito 文档:

public static T any(java.lang.Class clazz)

Matches any object, including nulls

This method doesn't do type checks with the given parameter, it is only there to avoid casting in your code. This might however change (type checks could be added) in a future major release.

所以在设计上它没有执行我希望的类型检查。我将不得不想出另一种方法来设计这些测试。但这解释了为什么他们的行为不像我预期的那样。

您要查找的方法是 isA,而不是 any