Shivanshu Goyal
Shivanshu Goyal

Reputation: 530

Mockito test case for repository layer EntityManager chained methods

Repository code to be tested using Mockito:

public List<X> findAll() {

CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<X> criteriaQuery = criteriaBuilder.createQuery(X.class);
Root<X> policyRoot = criteriaQuery.from(X.class);

return entityManager.createQuery(criteriaQuery.select(policyRoot)).getResultList();

}

How to mock cretedQuery() and getResultList() methods of entityManger?

@Test
public void testCase() {
when(entityManager.getCriteriaBuilder()).thenReturn(new 
CriteriaBuilderImpl(any()));

Query query = new QueryImpl(any(), any(), any());
when(entityManager.createQuery(anyString())).thenReturn(query);
when(query.getResultList()).thenReturn(attributeList);

}

It throws NullPointerException.

Upvotes: 1

Views: 2892

Answers (1)

Sven
Sven

Reputation: 2553

Use mocks. Make sure the entityManager is injectable in the class you try to test. For a unit test I would definitely do a test like this. It does not test the database, but it does test all the calls that are done and the general application logic. I agree you should also write an integration test that will test the 'real' database call and result.

@RunWith(MockitoJUnitRunner.class)
public class QueryTest {
    @Mock
    TypedQuery<X> query;

    @Mock
    CriteriaBuilderImpl criteriaBuilder;

    @Mock
    CriteriaQuery<X> criteriaQuery;

    @Mock
    Root<X> policyRoot;

    @Mock
    EntityManager manager; // This mock should be injected in the class that is been tested

    @InjectMocks
    TestClass sut; //System Under Test

    @Test
    public void test() {
        when(manager.getCriteriaBuilder()).thenReturn(criteriaBuilder);
        when(criteriaBuilder.createQuery(any(X.class)).thenReturn(criteriaQuery);
        when(criteriaQuery.from(any(X.class)).thenReturn(policyRoot);
        when(criteriaQuery.select(eq(policyRoot))).thenReturn(criteriaQuery);
        when(manager.createQuery(eq(criteriaQuery)).thenReturn(query);
        when(query.getResultList()).thenReturn(Collections.emptyList());

        List<X> result = sut.findAll();

        // now verify
        verify(manager, times(1)).getCriteriaBuilder();
        verify(criteriaBuilder, times(1)).createQuery(any(X.class));
        // and so on

        // now write your assertions
        assertEquals(0, result.getSize());
    }
}

Upvotes: 1

Related Questions