Mockito 如何测试在方法内部创建的实例是否正在调用方法

Mockito How to test that an instance created inside a method is calling methods

假设我有这个功能:

fun method() {
   val obj = Obj()
   obj.callsMethod()
   obj.callsOtherMethod()
}

我怎样才能做类似于 verify(obj).callsMethod() 的事情?有没有其他方法可以测试这个方法?

你有三个选择:

  1. 使用注入
  2. 使用PowerMockito
  3. 以测试友好的方式重构代码

使用注入

如果对象 Obj 被注入到你的 class 测试中,而不是已经在方法中初始化,你将能够注入一个 mock 然后使用表达式

verify(obj).callsMethod()

你已经知道了,没错。

使用 PowerMockito

使用 powermockito 你可以写这样的东西

@RunWith(PowerMockRunner.class)
@PrepareForTest({Obj.class})
class MyJunit{
....
@Test
public void test() throws Exception{
Obj myMock = Mockito.mock(Obj.class);
PowerMockito.whenNew(Obj.class).withAnyArguments().thenReturn(myMock);

// here your test
}

这时候你就可以用你已经知道的表达方式了

重构

您可以使用 protected 方法来构建 Obj 并在您的 junit 中模拟此方法以 return Obj 的模拟版本,然后使用你已经知道的表达是正确的。