我试图用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我希望这是因为我在when中调用了query,但是我不能单独地模拟query。我怎么嘲笑?
发布于 2020-04-18 11:48:35
请更正:
Query mockedQuery = mock(Query.class); //!
when(mockedQuery.getSingleResult()).thenReturn(fixture); //!! ;)
when(entityManagerMock.createNativeQuery(anyString())).thenReturn(mockedQuery);我希望这能解释,null和“未完成的固执”起源于何处。(您必须模拟“中间”的任何对象/调用)
这个^仅指“要被嘲弄的代码”,并且不假定“其他问题”(例如entityMangerMock != null)。
发布于 2020-04-18 12:29:33
when(entityManagerMock.createNativeQuery(Mockito.anyString()).getSingleResult()).thenReturn(fixture);
如果实体管理器是一个模拟,那么您就不能跨越几个方法,因为默认情况下,模拟返回null的所有方法都是空的,您应该分两个步骤:
Query queryMock = Mockito.mock(Query.class);
when(entityManagerMock.createNativeQuery(Mockito.anyString()).thenReturn(queryMock);
when(queryMock.getSingleResult()).thenReturn(fixture);希望这将是有用的!
https://stackoverflow.com/questions/61288441
复制相似问题