1

I have a unit test that fails only some of the time with this error:

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

The test is below. There are various questions here on this particular error, with the main cause seeming to be nested mocking (Hint 3 above):

Unfinished Stubbing Detected in Mockito

but I don't think this is the case here, given that the test passes most of the time?

@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());
}

The test is failing on this line:

Mockito.doAnswer(a).when(channel).basicPublish(Mockito.any(), Mockito.eq("testQueue"), Mockito.any(), Mockito.eq(data));
rmf
  • 625
  • 2
  • 9
  • 39
  • Do you absolutely need to start running your test (by starting your publisher thread) before you've finished setting up your mocks? – tgdavies Nov 23 '20 at 09:23
  • @tgdavie Probably not, I could move the `Mockito.doAnswer` above the `t.start()`. Do you suspect that may be why this test fails randomly? Would this account for the mockito error message I am seeing? – rmf Nov 23 '20 at 13:04
  • 1
    I'm not sure, but it may make the test more consistent. – tgdavies Nov 23 '20 at 21:14

0 Answers0