当该方法在基类内部并且测试方法类将其扩展时,如何模拟方法呼叫JUNIT



我需要在junit中编写单元测试以获取方法,该方法在A类中,A类扩展了B类B。我的测试方法netawing Methoda((调用另一个Methodb((,它在内部因此,B类。我应该如何模拟此MethodB((调用,以便当我从testCase调用Methoda((时,当它调用MethodB((时,它会获取模拟的值并通过测试案例通过?我应该嘲笑哪个课程,班级或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时,您必须监视班级,因此会嘲笑一些mehtods,因为其余的称为原始内容:

@Test
public void methodATest() {
    ClassA obj = Mockito.spy(ClassA.class);
    Mockito.when(obj.methodB()).thenReturn(6);
    Assert.assertEquals(10, obj.methodA());
}

相关内容

  • 没有找到相关文章

最新更新