Try to search your question here, if you can't find : Ask Any Question Now ?

Mockito always return NULL when test hibernate method

HomeCategory: stackoverflowMockito always return NULL when test hibernate method
Avatarsourav asked 5 days ago

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

1 Answers
Best Answer
Avatarnaveen answered 5 days ago
Your Answer

9 + 2 =

Popular Tags

WP Facebook Auto Publish Powered By : XYZScripts.com