gpt4 book ai didi

java - CriteriaQuery 返回 nullpointerexception mockito

转载 作者:行者123 更新时间:2023-11-28 21:26:51 25 4
gpt4 key购买 nike

我正在使用 mockito 开始我的测试。首先我需要测试 .findAll() 这是一个 CriteriaQuery...

UserFacade 扩展了具有这个 findAll 的 AbstractFacade。

public abstract class AbstractFacade<T> {

private Class<T> entityClass;

public AbstractFacade(Class<T> entityClass) {
this.entityClass = entityClass;
}

protected abstract EntityManager getEntityManager();

....

public List<T> findAll() {
CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
CriteriaQuery<T> cq = cb.createQuery(entityClass);
Root<T> rootEntry = cq.from(entityClass);
CriteriaQuery<T> all = cq.select(rootEntry);
TypedQuery<T> allQuery = em.createQuery(all);
return allQuery.getResultList();
}
...

我的测试:

@RunWith(MockitoJUnitRunner.class)
public class UserFacadeTest {

public UserFacadeTest() {
}
@Mock
private EntityManager mockedEM;
@Mock
private CriteriaQuery mockedCQ;
@Mock
private CriteriaQuery mockedCQAll;
@Mock
private Root mockedRoot;
@Mock
private CriteriaBuilder mockedCB;
@Mock
private TypedQuery mockedTQ;
private UserFacade userFacade;
List<User> userList= new ArrayList<>();

@Before
public void setUp() {
userFacade=new UserFacade();
userFacade.setEm(mockedEM);
when(mockedEM.getCriteriaBuilder()).thenReturn(mockedCB);
when(mockedCB.createQuery()).thenReturn(mockedCQ);
when(mockedCQ.from(User.class)).thenReturn(mockedRoot);
when(mockedCQ.select(mockedRoot)).thenReturn(mockedCQAll);
when(mockedEM.createQuery(mockedCQAll)).thenReturn(mockedTQ);
when(mockedTQ.getResultList()).thenReturn(userList);
}

@Test
public void testFindAll() {
System.out.println("findAll");
User user = new User(1, "username", "password", "email", new Date());
userFacade.create(user);
verify(mockedEM, times(1)).persist(any());
userList.add(user);
//next line cause NullPointerException
List list=userFacade.findAll();

assertTrue("Should return 1", 1==list.size());

}

调试我的测试我看到了这个:

    ....

public List<T> findAll() {
CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
CriteriaQuery<T> cq = cb.createQuery(entityClass); //cq is null!!!!
Root<T> rootEntry = cq.from(entityClass); //cq is null!!!!
CriteriaQuery<T> all = cq.select(rootEntry);
TypedQuery<T> allQuery = em.createQuery(all);
return allQuery.getResultList();
}
...

所以我认为传递“User.class”是错误的...我也必须 mock 这个???怎么办?

最佳答案

如我所见,您没有正确地 mock 它。

when(mockedCB.createQuery()).thenReturn(mockedCQ);

因此,当 mockedCB.createQuery() 被调用时,mockedCQ 将被返回。但是,在你的代码中你有 cb.createQuery(entityClass); 这不是同一个方法。所以尝试将其更改为

when(mockedCB.createQuery(any())).thenReturn(mockedCQ);

关于java - CriteriaQuery 返回 nullpointerexception mockito,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38158477/

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