简体   繁体   English

Mockito 正在调用主类的方法

[英]Method from main class is getting called for Mockito

I am writing a test class for one of the method in my class.我正在为我班上的一个方法编写一个测试类。 I can't make much changes in the class.我不能在课堂上做太多改变。 Below is a simpler version of my code.下面是我的代码的一个更简单的版本。

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
    }
}

Below is my test method下面是我的测试方法

@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);
    }
  }

The first two doReturn 's are returning correct values but getObject() method is calling the method from the class and is not returning the stubbed value.前两个 doReturn 正在返回正确的值,但 getObject() 方法正在从类中调用该方法并且不返回存根值。 I tried returning mock instance by using PowerMockito.whenNew but that did not work.我尝试使用 PowerMockito.whenNew 返回模拟实例,但这不起作用。 Any pointers will be helpful.任何指针都会有所帮助。

You could move the new instance creation into a new function like this:您可以将新实例创建移动到一个新函数中,如下所示:

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

Now, you can modify getListForNext(...) function to:现在,您可以将 getListForNext(...) 函数修改为:

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

Now return a mock or a spy of AIterator for the newly created getIteratorInstance() function:现在为新创建的 getIteratorInstance() 函数返回 AIterator 的模拟或间谍:

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

Your test should execute now.您的测试应该立即执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM