模拟测试DAO在createcricriteria得到NullPointerException



我正在尝试为dao层编写测试。我从hibernate工作,当我尝试测试我的方法getAll时,我从createCriteria获得异常NullPointerException,我不知道如何解决问题。

这是我的例外:

java.lang.NullPointerException
    at dao.UserDaoTest.testFindAll(UserDaoTest.java:69)

这是我的测试类:

@Mock
private SessionFactory sessionFactory;
@Mock
private Session session;
@Mock
private Transaction transaction;
@InjectMocks
private UserDaoImpl userDao;
private User user;
@Before
public void setUpUser(){
    user = new User();
    user.setName("is name");
    when(sessionFactory.openSession()).thenReturn(session);
    when(session.beginTransaction()).thenReturn(transaction);
}
@Test
public void testFindAll(){
    List<User> userList = new ArrayList<>();
    userList.add(user);
    when(session.createCriteria(User.class).list()).thenReturn(userList); //NullPointerException
    List<User> userList1 = userDao.findAll();
    assertThat(userList1, is(userList));
}

这是Dao类:

private Session session;
private Transaction transaction;
public List<User> findAll() {
    List<User> userList = null;
    session = sessionFactory.openSession();
    transaction = null;
    try{
        transaction = session.beginTransaction();
        userList = session.createCriteria(User.class).list();
        transaction.commit();
    }catch (HibernateException e) {
        if (transaction!=null) {
            transaction.rollback();
        }
        e.printStackTrace();
    }finally {
        session.close();
    }
    return userList;
}

在testFindAll()

中试试这样做
Criteria aCriteria = Mockito.mock(Criteria.class);
when(session.createCriteria(User.class)).thenReturn(aCriteria);
when(aCriteria.list()).thenReturn(userList);

相关内容

  • 没有找到相关文章

最新更新