Mockito always return NULL when test hibernate method

Nguyễn Vũ Hoàng :

I have some hibernate methods and when i test them, mockito always return null instead of expected value

This is my hibernate method

@Autowired
private SessionFactory sessionFactory;

public StudentDAO() {

}
public List<StudentDetail> listStudentDetail() {
    String hql = "Select new " + StudentDetail.class.getName() //
            + "(s.studentid,s.name,s.address) " //
            + " from " + Student.class.getName() + " s ";
    Session session = this.sessionFactory.getCurrentSession();
    Query<StudentDetail> query = session.createQuery(hql, StudentDetail.class);
    List<StudentDetail> list =null;
    list = query.getResultList();
    return list;
}

And this is my test method

@Mock
SessionFactory sessionFactory;
@Mock
Query query;
@Mock
Session session;
@Mock
List<StudentDetail> list;
@InjectMocks
private StudentDAO studentDAO ;

// Test get method

@Test
public void getListStudentTest() {
    StudentDetail sd1 = new StudentDetail(1, "A", "X");
    Mockito.when(query.getResultList()).thenReturn(list);
    Mockito.when(sessionFactory.getCurrentSession()).thenReturn(session);
    Mockito.when(session.createQuery(ArgumentMatchers.anyString())).thenReturn(query);
    Mockito.verify(sessionFactory.getCurrentSession());
    Mockito.verify(session.createQuery(ArgumentMatchers.anyString(),ArgumentMatchers.anyObject() ));
    Mockito.verify(query.getResultList());

    Assert.assertEquals(sd1, studentDAO.listStudentDetail().get(0));
}

When i run my web app, studentDAO.listStudentDetail() return true value normally but in test method its always return null

ETO :

Here

Assert.assertEquals(sd1, studentDAO.listStudentDetail().get(0));

the studentDAO.listStudentDetail() returns a mock list. You didn't mock its .get method. Thus it returns null by default. You should modify your assertEquals check:

Assert.assertEquals(list, studentDAO.listStudentDetail());

(You don't need the sd1 object at all)


Also you are not using verify properly. You should do like this:

Mockito.verify(sessionFactory).getCurrentSession();
Mockito.verify(session).createQuery(ArgumentMatchers.anyString());
Mockito.verify(query).getResultList();

(note the closing parenthesis before .)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=306549&siteId=1