只是想问一下,因为我被困在测试用例中并得到错误,因为“实际上,与这个模拟的交互为零”。
我已经创建了一个正在执行 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();
}
}
对于上述类(class),我正在使用 Mockito 构建测试。因此,对于我上面的 saveEmployee 方法 Session,TRAnsaction,我已经将其作为 Mock 对象,现在我还需要检查 session 、save 方法 和事务。
所以我写了下面的 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 个值将被添加到数据库,但我的测试用例将失败,因为交互为零。
最佳答案
测试中的 Session mock 与 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();
}
}
关于java - Mockito 测试失败 : Actually, 与此模拟的交互为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41744872/