Java JMockit-相同类型的两个模拟实例

Java JMockit-相同类型的两个模拟实例,java,unit-testing,testing,mocking,jmockit,Java,Unit Testing,Testing,Mocking,Jmockit,我正在使用JMockit框架,并尝试测试我的简单的EventBus实现,它允许EventHandlers为事件类型注册。在事件总线上触发事件时,所有注册的处理程序都会收到通知。事件处理程序可以使用事件,这将导致后续处理程序不会收到事件通知 我的测试方法如下所示: // The parameter secondHandler should be mocked automatically by passing it // as an argument to the test method @Test

我正在使用JMockit框架,并尝试测试我的简单的
EventBus
实现,它允许
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;
        }
    };
}
异常发生在
times=0
行,我不知道为什么,因为类型
secondHandler
应该被模拟,因为它是作为参数传递给测试方法的。将
@Mocked
@Injectable
添加到参数中没有区别

如果我从
firstHandler
生成一个标准类,它将只使用事件,然后测试代码,那么一切都会正常运行。但在这种情况下,我无法明确验证是否调用了
firstHandler
的方法
handleEvent
,因为它不再是模拟类型


非常感谢您的帮助,谢谢

我自己找到了解决问题的办法。修复相当简单,我只需要将
验证
块转换为
期望
块,并将其放在模拟的
firstHandler
初始化之前

在我看来,语句
new MockUp()
模拟每种类型的
EventHandler
,并覆盖已经定义的实例,即my
secondHandler
。无论我是否正确,或者它是一个bug还是一个特性,我都不知道


如果有人知道到底发生了什么,请对这个答案发表评论。谢谢

在最初的测试中,
EventHandler
类被模拟了两次,首先是使用Expectations API(作为“secondHandler”参数),然后再次使用Annotations API(类实例化)。第二次嘲弄改写了第一次嘲弄。这两个模拟API可以一起使用,但不能在同一测试中模拟相同的类型。
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