JMockit - 相同类型的两个模拟实例
我正在使用 JMockit 框架,并且正在尝试测试我的简单 EventBus
实现,该实现允许为 Event
类型注册 EventHandlers
。当事件在事件总线上触发
时,所有注册的处理程序都会收到通知。事件可以被事件处理程序使用,这将导致后续处理程序不会收到该事件的通知。
我的测试方法如下所示:
// The parameter secondHandler should be mocked automatically by passing it
// as an argument to the test method
@Test
public void testConsumeEvent(final EventHandler<TestEvent> secondHandler)
{
// create the event which will be fired and which the handlers are
// listening to
final TestEvent event = new TestEvent();
// this handler will be called once and will consume the event
final EventHandler<TestEvent> firstHandler =
new MockUp<EventHandler<TestEvent>>()
{
@Mock(invocations = 1)
void handleEvent(Event e)
{
assertEquals(event, e);
e.consume();
}
}.getMockInstance();
// register the handlers and fire the event
eventBus.addHandler(TestEvent.class, firstHandler);
eventBus.addHandler(TestEvent.class, secondHandler);
eventBus.fireEvent(event);
new Verifications()
{
{
// verify that the second handler was NOT notified because
// the event was consumed by the first handler
onInstance(secondHandler).handleEvent(event);
times = 0;
}
};
}
当我尝试运行此代码时,出现以下异常:
java.lang.IllegalStateException: Missing invocation to mocked type at this
point; please make sure such invocations appear only after the declaration
of a suitable mock field or parameter
异常发生在 times = 0
行上,我不知道为什么,因为类型 secondHandler
应该被模拟,因为它作为参数传递给测试方法。在参数中添加 @Mocked
或 @Injectable
没有什么区别。
如果我从 firstHandler
创建一个标准类,它只会消耗事件,然后测试代码,一切都会运行得很好。但在这种情况下,我无法明确验证 firstHandler
的方法 handleEvent
是否被调用,因为它不再是模拟类型。
非常感谢任何帮助,谢谢!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我自己找到了问题的解决方案。修复相当简单,我只需要将
Verifications
块转换为Expectations
块,并将其放在模拟的firstHandler
初始化之前。在我看来,语句
new MockUp>()
模拟每种类型的EventHandler
并覆盖已经定义的实例,即我的第二个处理程序
。我不知道我是否正确,或者这是一个错误还是一个功能。如果有人知道到底发生了什么,请对此答案发表评论。谢谢!
I have found solution of the problem myself. The fix was rather simple, I just needed to transform the
Verifications
block into anExpectations
block and put it BEFORE the initialization of the mockedfirstHandler
.It seems to me that the statement
new MockUp<EventHandler<TestEvent>>()
mocks every type ofEventHandler<TestEvent>
and overrides already defined instances, i.e. mysecondHandler
. Whether I'm correct or not or whether it's a bug or a feature I don't know.If someone knows what exactly is going on, please comment on this answer. Thanks!