使用Mockito模拟hibernate的SessionFactory的问题

Abh*_*nia 4 java hibernate mocking mockito

知道为什么下面的模拟代码不起作用?

org.hibernate.SessionFactory sessionFactory = Mockito.mock(SessionFactory.class);
org.hibernate.Session session = Mockito.mock(Session.class);
Mockito.when(sessionFactory.getCurrentSession()).thenReturn(session);
Run Code Online (Sandbox Code Playgroud)

thenReturn语句不编译."OngoingStubbing类型中的方法thenReturn(Session)不适用于参数(Session)"但是,为什么它不适用?我想我的进口是正确的.

ska*_*man 9

这是因为实际返回的类型SessionFactory.getCurrentSession()org.hibernate.classic.Session,它是子类型org.hibernate.Session.您需要将模拟更改为正确的类型:

org.hibernate.classic.Session session = Mockito.mock(org.hibernate.classic.Session.class);
Run Code Online (Sandbox Code Playgroud)