0
我正在嘗試爲dao圖層寫入測試。我從休眠的工作,當我試圖測試我的方法getAll
我得到異常NullPointerException
從createCriteria
行,我不知道如何解決問題。Mockito在createCriteria中測試DAO獲取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;
}
您必須將'createCriteria'存根返回。然後你必須存儲一些東西來返回一個「列表」。沒有捷徑。 –
@SotiriosDelimanolis,我需要在DAO類中爲stub創建字段Criteria? –