Search code examples
javaunit-testingjunitmockitoentitymanager

How to mock and unit test javax.persistence.EntityManager and javax.persistence.Query? Getting NullPointerException


While testing a method. I have come across entity manager to which I need to pass a query.

StringBuilder jpqlQuery=new StringBuilder("select Distinct s.modelCode from Model s where 1=1");
Query query = entityManager.createQuery(jpqlQuery.toString());
    if(myModel != null ) {      
        jpqlQuery.append(" and s.name = :name");
}
if(myModel != null){
    query.setParameter("name", myModel.getFirstName());
}

I am able to enter the jpqlquery.append condition but not able to get inside query.setParameter.

I get NullPointerException at Query query = entityManager.createQuery(jpqlQuery.toString());

Below is my test method:

@Test
public void testGetModelNameDetails() {
    List<String> results = new ArrayList<>();
    ModelDTO myModel = Mockito.mock(ModelDTO.class);
    StringBuilder jpqlQuery = new StringBuilder("select Distinct s.modelCode from Model s where 1=1");
    when(myModel.getFirstName()).thenReturn("Downtown");
    when(em.createQuery(jpqlQuery.toString())).thenReturn(query);
    when(query.getResultList()).thenReturn(results);
    serviceImpl.getNameDetails(myModel);
}

At line when(em.createQuery(jpqlQuery.toString())).thenReturn(query); while debugging I can see that the query object is mocked query object. But inside the method being tested i.e. at this line: Query query = entityManager.createQuery(jpqlQuery.toString()); the query object is null.

Hence I get NullPointerException at query.setParameter("name", myModel.getFirstName());

At the start of the Test class I am mocking entityManager and query @Mock EntityManager entityManager;

@Mock
Query query;

@Before
public void setUp() {

    MockitoAnnotations.initMocks(this);
    entityManager = Mockito.mock(em.class);
    query = Mockito.mock(Query.class);
}

What am I missing here or doing wrong?


Solution

  • Solved! when(entityManager.createQuery(Mockito.anyString())).thenReturn(query);