首页 > 解决方案 > 检测到 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单独模拟。我该如何嘲讽?

标签: javaunit-testingjunitmockingmockito

解决方案


请更正:

Query mockedQuery = mock(Query.class); //!
when(mockedQuery.getSingleResult()).thenReturn(fixture); //!! ;)
when(entityManagerMock.createNativeQuery(anyString())).thenReturn(mockedQuery);

我希望这能解释null“未完成的存根”的起源。(你必须模拟任何对象/调用“中间”)


此 ^ 仅指“要模拟的代码”,并假定没有“其他问题”(例如entityMangerMock != null


推荐阅读