1

I am trying to unit test a service with entityManager

Service code to be Mocked:

Query query = entityManager.createNativeQuery(sqlQuery);

Object[] object = (Object[]) query.getSingleResult();

Test Code Mocking:

when(entityManagerMock.createNativeQuery(Mockito.anyString()).getSingleResult()).thenReturn(fixture);

This results in Null Pointer Exception

However since Mockito.anyString() returns empty string by default createNativeQuery might not be expecting it. So changed to below.

doReturn(fixture).when(entityManagerMock.createNativeQuery(Mockito.anyString()).getSingleResult());

but with this I get

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

I am expecting this is due to the fact I am calling createNativeQuery inside when but then I can't mock query separately. How do I mock?

garg10may
  • 5,794
  • 11
  • 50
  • 91
  • This might help you out: https://stackoverflow.com/questions/32343646/mockito-nullpointerexception-on-native-query – Wooopsa Apr 18 '20 at 11:49

2 Answers2

1

Please correct to:

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

I hope this explains, where the null and "Unfinished stubbing" originates. (you have to mock any object/call "in between")


This ^ refers only to "code to be mocked" and assumes no "other issues" (e.g. entityMangerMock != null)

xerx593
  • 12,237
  • 5
  • 33
  • 64
0

when(entityManagerMock.createNativeQuery(Mockito.anyString()).getSingleResult()).thenReturn(fixture);

if entity manager is a mock then you can't cross several methods because by default all methods for a mock return null, you should do it in two steps:

    Query queryMock = Mockito.mock(Query.class);    
 when(entityManagerMock.createNativeQuery(Mockito.anyString()).thenReturn(queryMock);
    when(queryMock.getSingleResult()).thenReturn(fixture);

Hope that this will be useful!

Lucbel
  • 339
  • 1
  • 4