Reputation: 2527
I'm testing a Spring service and I'd like to create use a mock session so I don't have to connect to the actual database.
Unfortunately:
org.mockito.exceptions.misusing.MissingMethodInvocationException:
when() requires an argument which has to be 'a method call on a mock'.
TweetServiceTest.java
Session session;
TweetService tweetService = new TweetServiceImpl();
@Before
public void setUp() throws Exception {
session = Mockito.mock(Session.class);
HibernateUtil hibernateUtil = Mockito.mock(HibernateUtil.class);
Mockito.when(hibernateUtil.getSession()).thenReturn(session);
}
HibernateUtil.java
public static Session getSession() {
Session session = null;
try {
session = HibernateUtil.getSessionFactory().getCurrentSession();
if (!session.isOpen()) {
session = HibernateUtil.getSessionFactory().openSession();
}
} catch (Exception e) {
e.printStackTrace();
}
return session;
}
Upvotes: 0
Views: 4000
Reputation: 692043
Mockito doesn't mock static methods. Only instance methods.
Mocking static methods would necessitate to redefine the class itself.
Mocking instance methods only needs to create an instance of a dynamically generated subclass which overrides all the methods of the superclasses.
Make your method an instance method (preferrably), or use PwerMockito which, AFAIK, allows mocking static methods (but is more complex and slower)
Upvotes: 3