首页 > 解决方案 > 从 mockito 检测到间歇性未完成的存根失败?

问题描述

我有一个单元测试仅在某些时候失败并出现此错误:

Unfinished stubbing detected here:
-> at com.example.testHandlePublish(MyTestClass.java:78)

E.g. thenReturn() may be missing.
Examples of correct stubbing:
    when(mock.isOk()).thenReturn(true);
    when(mock.isOk()).thenThrow(exception);
    doThrow(exception).when(mock).someVoidMethod();
Hints:
 1. missing thenReturn()
 2. you are trying to stub a final method, which is not supported
 3. you are stubbing the behaviour of another mock inside before 'thenReturn' instruction is completed

测试如下。这里有关于这个特定错误的各种问题,主要原因似乎是嵌套模拟(上面的提示 3):

在 Mockito 中检测到未完成的存根

但我认为情况并非如此,因为测试大部分时间都通过了?

@Test
public void testHandlePublish()
    throws IOException, InterruptedException
{
    BlockingQueue<Event<QueueConsumer>> consumerEvents = new LinkedBlockingQueue<>();
    BlockingQueue<Event<WorkerPublisher>> publisherEvents = new LinkedBlockingQueue<>();
    Channel channel = Mockito.mock(Channel.class);
    WorkerConfirmListener listener = Mockito.mock(WorkerConfirmListener.class);
    WorkerPublisher impl = new WorkerPublisherImpl(channel, metrics, consumerEvents, listener);
    EventPoller<WorkerPublisher> publisher = new EventPoller<>(2, publisherEvents, impl);
    Thread t = new Thread(publisher);
    t.start();
    publisherEvents.add(new WorkerPublishQueueEvent(data, "testQueue", taskInformation));
    CountDownLatch latch = new CountDownLatch(1);
    Answer<Void> a = invocationOnMock -> {
        latch.countDown();
        return null;
    };
    Mockito.doAnswer(a).when(channel).basicPublish(Mockito.any(), Mockito.eq("testQueue"), Mockito.any(), Mockito.eq(data));
    latch.await(5000, TimeUnit.MILLISECONDS);
    publisher.shutdown();
    Assert.assertEquals(0, publisherEvents.size());
    Assert.assertEquals(0, consumerEvents.size());
}

测试在这条线上失败:

Mockito.doAnswer(a).when(channel).basicPublish(Mockito.any(), Mockito.eq("testQueue"), Mockito.any(), Mockito.eq(data));

标签: javaunit-testingjunitmockitotestng

解决方案


推荐阅读