来自主类的方法被调用为Mockito

问题描述

我正在为类中的一种方法编写测试类。我不能在课堂上做很多改变。下面是我的代码的简单版本。

Class AInternal extend A {
    public List getList(listArg1,listArg2)  {
        boolean flag = isCorrectFlag();
        if (flag)  {
            return getListForNext(nextArg1,nextArg2);
        }
    }

    public boolean isCorrectFlag(){
        //logic and return value
    }

    protected List getListForNext(nextArg1,nextArg2)   {
        AIteror arit = new AIterator();
        String s  = fetchValue();
        arit.getobject();
    }

    protected class AIterator  {
        public Iterator getobject() {
            //logic and return iterator
        }
    }

}

Class A {
    public  String fetchValue() {
        //logic and return value
    }
}

下面是我的测试方法

@Test
public void getList() throws Exception {
    try {
      AInternal AInternalSpy = spy(new AInternal());
      AIterator AIteratorSpy = spy(AInternal.new AIterator());
      Iterator<Object> iterator1 = ep.iterator();
      doReturn(Boolean.TRUE).when(AInternalSpy).isCorrectFlag();
      doReturn("value").when(AInternalSpy).fetchValue();
      doReturn(iterator1).when(AIterator).getobject();
      
      AInternalSpy.getIteratorPartitions(arg1,arg2);

    }
    catch (IllegalArgumentException e) {
      throw new Exception(e);
    }
  }

前两个doReturn返回正确的值,但是getobject()方法从类中调用方法,并且不返回存根值。 我尝试通过使用powermockito.whenNew返回模拟实例,但这没有用。 任何指针都会有所帮助。

解决方法

您可以将新实例创建移动到新函数中,如下所示:

protected AIterator getIteratorInstance() {
    return new AIterator();
}

现在,您可以将getListForNext(...)函数修改为:

protected List getListForNext(nextArg1,nextArg2)   {
    AIteror arit = getIteratorInstance();
    String s  = fetchValue();
    arit.getObject();
}

现在为新创建的getIteratorInstance()函数返回AIterator的模拟或间谍:

doReturn(AIteratorSpy).when(AInternalSpy).getIteratorInstance()

您的测试应立即执行。