Criteria Query Mockito unit test - NullPointerExce

2019-07-26 09:11发布

问题:

I have a method that i'm trying to test using mockito. Below is the method i'm trying to test. I'm getting a null pointer exception when I run my test. I'm mocking Root but at accountEntity.get I'm getting null pointer. What am I missing here?

     public List<AccountEntity> createCriteriaQuery(final List<String> accountIdList,
                    final MultiValueMap<String, String> allRequestParams) {

                final CriteriaBuilder cb = entityManager.getCriteriaBuilder();           
                final CriteriaQuery<AccountEntity> cq = cb.createQuery(AccountEntity.class);
                final Root<AccountEntity> accountEntity = cq.from(AccountEntity.class);

                final Join<AccountEntity, PlanEntity> account = accountEntity.join(AccountEntity_.planEntity);

                final List<Predicate> predicates = new ArrayList<Predicate>();

        //Getting null pointer at the below call.        

**predicates.add(accountEntity.get(AccountEntity_.id).in(accountIdList));**

    /*remaining code here/

below is my test.

@InjectMocks
private AccountsDAO                         accountsDao;
@Mock
EntityManagerFactory                        entityManagerFactory;
@Mock
EntityManager                               entityManager;
@Mock
CriteriaBuilder                             cb;
@Mock
CriteriaQuery<AccountEntity>                cq;
@Mock
Root<AccountEntity>                         rootAccountEntity;
    @Test
        public void canGetAllAccountsInfo() {
        when(entityManagerFactory.createEntityManager()).thenReturn(entityManager);
        when(entityManager.getCriteriaBuilder()).thenReturn(cb); when(cb.createQuery(AccountEntity.class)).thenReturn(cq);
        when(cq.from(AccountEntity.class)).thenReturn(rootAccountEntity);
//Null pointer in the actual method call
            accountEntityList = accountsDao.createCriteriaQuery(accounIdList, allRequestParams);        
          }

回答1:

I would guess that accountEntity.get(AccountEntity_.id) resolves to null since you have not added any when(...).thenReturn(...) for the mocked accountEntity object in play.



回答2:

I was missing this statement

 when(accountEntity.get(AccountEntity_.id)).thenReturn(path);

I added this in the test class

    @Mock
    Path<String>                    path;

In the actual code for this to pass

predicates.add(accountEntity.get(AccountEntity_.id).in(accountIdList))

I need this

when(accountEntity.get(AccountEntity_.id)).thenReturn(path);