只是想问一下,因为我被困在测试用例中并且因为&#34而出现错误;实际上,与这个模拟器没有交互#34;
我创建了一个正在进行CRUD操作的Dao实现类。
public class EmployeeDaoImpl implements EmployeeDao {
@Override
public void saveEmployee(EmployeeDetails employee) {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
session.save(employee);
transaction.commit();
session.close();
}
}
对于上述课程,我正在使用Mockito构建测试。所以对于我上面的saveEmployee方法Session,TRansaction我把它作为Mock对象,现在我需要检查会话,保存方法和事务。
所以我在下面写了Mockito代码:
/ ** * * /
package sandeep.test;
import static org.junit.Assert.*;
import javax.transaction.HeuristicMixedException;
import javax.transaction.HeuristicRollbackException;
import javax.transaction.RollbackException;
import javax.transaction.SystemException;
import javax.transaction.Transaction;
import junit.framework.Assert;
import org.hibernate.Session;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import sandeep.DAO.EmployeeDao;
import sandeep.DAOImpl.EmployeeDaoImpl;
import sandeep.DAOImpl.HibernateUtil;
import sandeep.pojo.EmployeeDetails;
import static org.mockito.Mockito.*;
/**
* @author sandeep
*
*/
@RunWith(MockitoJUnitRunner.class)
public class EmployeeDaoImplTest {
@Mock
EmployeeDetails edt;
@Mock
Session session ;
@Mock
Transaction transaction;
@InjectMocks
EmployeeDaoImpl edi = new EmployeeDaoImpl();
@Before
public void setUp() throws Exception {
//eimpl = new EmployeeDaoImpl();
//emp= mock(EmployeeDao.class);
}
@After
public void tearDown() throws Exception {
}
@Test
public void testSaveEmployee(){
edi.saveEmployee(getEmployeeDetails());
// But here i am getting the error as zero interactions
verify(session, times(1)).save(EmployeeDetails.class);
}
public EmployeeDetails getEmployeeDetails(){
edt = new EmployeeDetails();
edt.setEname("sandeep");
edt.setId(2);
edt.setEnumber("hoi");
return edt;
}
}
我调试了代码,代码传递到我IDE中的所有断点,当我执行这3个值时,它将被添加到数据库中,但我的测试用例将因为没有交互而失败。
答案 0 :(得分:1)
您的测试中的Session模拟与EmployeeDaoImpl中使用的对象不同#saveEmployee
使用Session参数为EmployeeDaoImpl实现构造函数,并在saveEmployee()方法中使用该参数。这允许您的@InjectMocks按预期工作。
@RunWith(MockitoJUnitRunner.class)
public class MockitoTest {
@Mock
Session session;
@InjectMocks
EmployeeDaoImpl edi;
@Test
public void testSaveEmployee(){
edi.saveEmployee();
verify(session, times(1)).save();
}
}
class Session {
void save() {
System.out.println("saving");
}
}
interface EmployeeDao {
void saveEmployee();
}
class EmployeeDaoImpl implements EmployeeDao {
private Session session;
public EmployeeDaoImpl(Session session) {
this.session = session;
}
@Override
public void saveEmployee() {
session.save();
}
}