在被测试的方法中模拟对另一个 class 的另一个方法的调用

Mocking the call to another method of another class inside the method being tested

我正在测试一个方法 A,该方法调用另一个 class C 的另一个方法 B,其中 returns 一个 Object 类型 D。我想使用 mockito 模拟对 B() 的调用。我怎么做?

代码:

function A()
{
   /*some code here*/
   C c = createC();
   D d= null;
   d = c.B(args);
   /*some code here*/
}

首先,不是创建 C 的实际实例,而是创建它的 Test Double 版本,如下所示:

// Let's import Mockito statically so that the code looks clearer
import static org.mockito.Mockito.*;

// mock creation
C mockedC = mock(C.class);

然后在 mockedC 发生某些事情时定义您的 期望 ,例如:

when(mockedC.B(args)).thenReturn(new D());

它说,每当有人在 mockedC returns 上调用 B(args)D

最后,您可以验证 实际交互与预期交互,例如:

verify(mockedC)...

有关详细信息,请参阅 docs