Junit org.mockito.exceptions.misusing.unfinishedstubingexception
在DAO中为getSession方法编写测试类时,我遇到了一些问题 代码如下Junit org.mockito.exceptions.misusing.unfinishedstubingexception,junit,mockito,Junit,Mockito,在DAO中为getSession方法编写测试类时,我遇到了一些问题 代码如下 Test class import org.hibernate.SessionFactory; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import static org.mockito.Mockito.when; public
Test class
import org.hibernate.SessionFactory;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import static org.mockito.Mockito.when;
public class SessionDaoImplTest {
private SessionDaoImpl sessionDao;
@Mock
private SessionFactory session;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
sessionDao = new SessionDaoImpl(session);
}
@Test
public void testGetCurrentSession() throws Exception {
when(sessionDao.getCurrentSession()).
thenReturn(session.getCurrentSession());
}
}
受试班级
import com.oleg.project.dao.Session.SessionDao;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
public class SessionDaoImpl implements SessionDao {
@Autowired
private SessionFactory sessionFactory;
SessionDaoImpl(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public Session getCurrentSession() {
Session session = sessionFactory.getCurrentSession();
return session;
}
}
堆栈跟踪
org.mockito.exceptions.misusing.unfinishedstubingexception:
此处检测到未完成的存根:
->请访问com.oleg.project.dao.Session.impl。
testGetCurrentSession(sessiondaoimpletst.java:28)
变量
sessionDao
不是模拟变量
我想你的意思是sessionDao=spy(新sessiondaimpl(session))代码>
编辑:
您还必须将session.getCurrentSession()
提取到局部变量中:
Session currentSession = session.getCurrentSession();
when(sessionDao.getCurrentSession()).thenReturn(currentSession);
变量sessionDao
不是模拟变量
我想你的意思是sessionDao=spy(新sessiondaimpl(session))代码>
编辑:
您还必须将session.getCurrentSession()
提取到局部变量中:
Session currentSession = session.getCurrentSession();
when(sessionDao.getCurrentSession()).thenReturn(currentSession);
为什么?Session currentSession=Session.getCurrentSession();这与返回(session.getCurrentSession())相同;我认为您不能在存根另一个模拟对象(sessionDao
)的方法时使用模拟对象(sessionDao
)为什么???Session currentSession=Session.getCurrentSession();这与返回(session.getCurrentSession())相同;我认为您不能在存根另一个模拟对象(sessionDao
)的方法时使用模拟对象(sessionDao
)