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?