我需要在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);
}
答案 0 :(得分:0)
当ClassA扩展ClassB时,您必须监视ClassA,因此将模仿某些方法,其余方法称为原始方法:
@Test
public void methodATest() {
ClassA obj = Mockito.spy(ClassA.class);
Mockito.when(obj.methodB()).thenReturn(6);
Assert.assertEquals(10, obj.methodA());
}