如何模拟嵌套函数?

How to mock a nested function?

我有下面这个 class A. 它有两个函数 Barney 和 Ted。巴尼从里面给泰德打电话。如何在我的测试中模拟 Ted 的行为 class?

package MockingNestedFunction;

import java.util.ArrayList;
import java.util.List;

public class A
{
    public String Barney()
    {
        List<String> x =Ted();
        String a="";
        for(int i=0;i<x.size();i++)
        {
            a=a.concat(x.get(i));
        }
        return a;
    }

    public List<String> Ted()
    {
        List<String> x=new ArrayList<>();
        x.add("A");
        x.add("B");
        x.add("C");
        return x;
    }
}
package MockingNestedFunction;

import org.mockito.MockitoAnnotations;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import java.util.ArrayList;
import java.util.List;

import static org.mockito.Mockito.when;
import static org.testng.Assert.*;

public class ATest
{
    private A a;
    @BeforeMethod
    public void setup()
    {
        MockitoAnnotations.openMocks(this);
        a=new A();
    }

    @Test
    public void testA() throws Exception
    {
        List<String> x=new ArrayList<>();
        x.add("D");
        x.add("E");
        x.add("F");
        when(a.Ted()).thenReturn(x);
    }
}

when(a.Ted()).thenReturn(x) returns 错误,when() 需要一个必须是 'a method call on a mock' 的参数。 如何有效地模拟这个?

您没有将 mock 上的方法调用传递给 Mockito.when,正如错误消息所说的那样。您正在对自己创建的对象传递方法调用。

如果你需要对被测对象的一些方法进行存根,你正在寻找间谍。

@Spy
private A a;

@BeforeMethod
public void setup() {
    MockitoAnnotations.openMocks(this);
}

正如其他人在评论中指出的那样,如果您可以考虑重构代码,在被测对象上存根某些方法是一种有问题的做法。

最重要的是:让我们保持术语准确。您的代码中没有嵌套函数。