java - 检测到 Mockito 空指针异常和未完成的存根
问题描述
我正在尝试对 a 进行单元service
测试entityManager
要模拟的服务代码:
Query query = entityManager.createNativeQuery(sqlQuery);
Object[] object = (Object[]) query.getSingleResult();
测试代码模拟:
when(entityManagerMock.createNativeQuery(Mockito.anyString()).getSingleResult()).thenReturn(fixture);
这导致空指针异常
但是,由于Mockito.anyString()
默认情况下返回空字符串createNativeQuery
可能并不期望它。于是改成下面。
doReturn(fixture).when(entityManagerMock.createNativeQuery(Mockito.anyString()).getSingleResult());
但有了这个我得到
org.mockito.exceptions.misusing.UnfinishedStubbingException:
Unfinished stubbing detected here:
-> at com.novartis.idot.service.SrapiSapMeetingServiceTest.testFindById(SrapiSapMeetingServiceTest.java:112)
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 if completed
我期待这是因为我在createNativeQuery
里面打电话when
但我不能query
单独模拟。我该如何嘲讽?
解决方案
请更正:
Query mockedQuery = mock(Query.class); //!
when(mockedQuery.getSingleResult()).thenReturn(fixture); //!! ;)
when(entityManagerMock.createNativeQuery(anyString())).thenReturn(mockedQuery);
我希望这能解释null
“未完成的存根”的起源。(你必须模拟任何对象/调用“中间”)
此 ^ 仅指“要模拟的代码”,并假定没有“其他问题”(例如entityMangerMock != null
)
推荐阅读
- terraform - 模块内部无法识别配置的提供程序
- amazon-s3 - 将批量 csv 数据上传到现有 DynamoDB 表中
- html - 移动菜单以 HTML 格式放大整个网站
- elixir - 在长生不老药中访问中间结果
- javascript - 使用 vue-flatpickr-component 时,“Object(...) 不是函数”和“this.$refs.root 未定义”
- javascript - 在javascript +浏览器兼容性中隐藏日期和时间显示中的日期
- shared-memory - 尝试在不丢失当前信息的情况下扩展共享内存区域
- kubernetes - 如何使用 initContainers 检查 cassandra 是否已启动并正在运行
- mocha.js - 摩卡期望的行为不符合预期
- python - 从 discord.py 开始