我需要在JUnit中为一个方法编写单元测试,该方法位于类A内部,类A扩展类B。我的测试方法methodA()调用另一个位于类B内部的methodB()。那么我应该如何模拟这个 methodB() 调用,以便当我从 testCase 调用 methodA() 时,当它调用 methodB() 时,它会获取模拟值并让测试用例通过? 我应该模拟哪个类,A 类还是 B 类?
///logDaoImpl class extends BaseDaoImpl
@Override
public List<Log> LogAll(long fromIndex,long toIndex) {
String query = "from Log ";
QueryCondition qd = new QueryCondition();
qd.setIgnoreCount(false);
qd.addAndCondition("id", ">=" , "long", fromIndex);
List<Log> result = findByCustomNamedQuery(query, qd); //findByCustomNamedQuery method is from my extended class
return result;
}
public class BaseDaoImpl extends JpaDaoSupport implements BaseDao {
@PersistenceContext
EntityManager entityManager;
public List findByCustomNamedQuery(String query, QueryCondition qd) {
if (qd.hasConditions()) {
query += qd.getCondition() + qd.getOrderBy();
}
EntityManager em = getJpaTemplate().getEntityManagerFactory().createEntityManager();
Query q = em.createQuery(query);
String[] namedParams = StringUtils.substringsBetween(query, ":", " ");
if (namedParams != null) {
for (int i = 0; i < namedParams.length; i++) {
q.setParameter(namedParams[i], qd.getParamValue(namedParams[i]));
}
}
if (!qd.isIgnoreCount()) {
q.setFirstResult(qd.start());
q.setMaxResults(qd.count());
}
List result = q.getResultList();
em.close();
return result;
}
//test class
public void testLogAll() {
List<Log>expL=new ArrayList<Log>();
expL.add(Log);//added sample test log object from setup method
String query = "from Log ";
QueryCondition qd=new QueryCondition();
qd.setIgnoreCount(false);
qd.addAndCondition("id", ">=" , "long", 0L);
LogDaoImpl obj=Mockito.spy(LogDaoImpl.class);
when(obj.findByCustomNamedQuery(query,qd)).thenReturn(expL);
List<UnbanLog> expResult = expL;
List<UnbanLog> result = obj.LogAll(0L, 20L);
assertEquals(expResult, result);
}
最佳答案
当ClassA扩展ClassB时,你必须监视ClassA,因此一些方法将被mock,其余的称为原始方法:
@Test
public void methodATest() {
ClassA obj = Mockito.spy(ClassA.class);
Mockito.when(obj.methodB()).thenReturn(6);
Assert.assertEquals(10, obj.methodA());
}
关于java - 当方法位于基类内部并且测试方法类扩展它时,如何在 JUnit 中模拟方法调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56311124/