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));