gpt4 book ai didi

java - Criteria Query Mockito 单元测试 - NullPointerException

转载 作者:行者123 更新时间:2023-11-30 07:30:48 26 4
gpt4 key购买 nike

我有一个方法,我正在尝试使用mockito 进行测试。以下是我正在尝试测试的方法。当我运行测试时,出现空指针异常。我正在 mock 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);
}

最佳答案

我猜 accountEntity.get(AccountEntity_.id) 解析为 null 因为您没有添加任何 when(...).thenReturn( ...) 用于播放中的模拟 accountEntity 对象。

关于java - Criteria Query Mockito 单元测试 - NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36167148/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com