Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem mocking hibernate's SessionFactory using Mockito

Any idea why the following mocking code does not work?

org.hibernate.SessionFactory sessionFactory = Mockito.mock(SessionFactory.class);
org.hibernate.Session session = Mockito.mock(Session.class);
Mockito.when(sessionFactory.getCurrentSession()).thenReturn(session);

The thenReturn statement does not compile. "The method thenReturn(Session) in the type OngoingStubbing is not applicable for the arguments (Session)" But, why is it not applicable? I think I have the imports figured out correctly.

like image 450
Abhijeet Kashnia Avatar asked Jan 22 '23 08:01

Abhijeet Kashnia


1 Answers

This is because the type actually returned by SessionFactory.getCurrentSession() is org.hibernate.classic.Session, which is a sub-type of org.hibernate.Session. You'll need to change your mock to the correct type:

org.hibernate.classic.Session session = Mockito.mock(org.hibernate.classic.Session.class);
like image 159
skaffman Avatar answered Jan 26 '23 10:01

skaffman