【问题标题】:Criteria Query Mockito unit test - NullPointerException条件查询 Mockito 单元测试 - NullPointerException
【发布时间】:2016-03-22 23:31:21
【问题描述】:

我有一个方法,我正在尝试使用 mockito 进行测试。以下是我正在尝试测试的方法。运行测试时出现空指针异常。我在嘲笑 Root 但在 accountEntity.get 我得到空指针。我在这里错过了什么?

     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/

下面是我的测试。

@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);        
          }

【问题讨论】:

    标签: java junit mockito


    【解决方案1】:

    我猜accountEntity.get(AccountEntity_.id) 会解析为null,因为你还没有为模拟的accountEntity 对象添加任何when(...).thenReturn(...)

    【讨论】:

      【解决方案2】:

      我错过了这个声明

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

      我在测试类中添加了这个

          @Mock
          Path<String>                    path;
      

      在此通过的实际代码中

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

      我需要这个

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

      【讨论】:

        猜你喜欢
        • 2021-11-29
        • 1970-01-01
        • 2020-05-03
        • 1970-01-01
        • 1970-01-01
        • 2020-09-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多