【发布时间】:2020-04-18 11:36:41
【问题描述】:
我正在尝试使用 entityManager 对 service 进行单元测试
要模拟的服务代码:
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
我期待这是因为我在when 内调用createNativeQuery 但我不能单独模拟query。我该如何嘲讽?
【问题讨论】:
-
这可能会对您有所帮助:stackoverflow.com/questions/32343646/…
标签: java unit-testing junit mocking mockito