【问题标题】:Mockito Null Pointer Exception and Unfinished stubbing detected检测到 Mockito 空指针异常和未完成的存根
【发布时间】:2020-04-18 11:36:41
【问题描述】:

我正在尝试使用 entityManagerservice 进行单元测试

要模拟的服务代码:

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。我该如何嘲讽?

【问题讨论】:

标签: java unit-testing junit mocking mockito


【解决方案1】:

请更正:

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

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


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

【讨论】:

    【解决方案2】:

    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);
    

    希望这会有用!

    【讨论】:

      猜你喜欢
      • 2020-09-07
      • 2017-04-07
      • 1970-01-01
      • 2021-12-06
      • 2014-12-06
      • 1970-01-01
      • 1970-01-01
      • 2015-10-07
      相关资源
      最近更新 更多