java - 从 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):
但我认为情况并非如此,因为测试大部分时间都通过了?
@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));
解决方案
推荐阅读
- python - 如何将字典列表转换为元组列表
- python - 是否可以为正在运行的 Python 程序设置文件权限
- python-3.x - Python 请求:分块发布请求
- select - 无法从 Katalon 工作室的下拉菜单中选择一个选项
- javascript - 如何在 ReactJS 中切换类 onClick?
- reactjs - 如何获取任何组件的道具类型?
- npm - 如何在苗条的 JS 应用程序中添加引导模块?
- laravel - 表上存在具有相同值的两列的 Laravel 验证
- java - 什么系统时钟 System.currentTimeMillis(); 在 centOS 上的 Java 中使用
- css - CSS - 来回动画 css 设置