当我使用 doReturn(..).when(....) 时,PowerMockito 正在调用该方法

Ahm*_*mad 5 java mockito powermockito

我是 PowerMockito 的新手,它显示的行为我不明白。以下代码解释了我的问题:

public class ClassOfInterest {

  private Object methodIWantToMock(String x) {

    String y = x.trim();

    //Do some other stuff;
  }

  public void methodUsingThePrivateMethod() {

    Object a = new Object();
    Object b = methodIWantToMock("some string");

    //Do some other stuff ...
  }
}
Run Code Online (Sandbox Code Playgroud)

我有一个类,其中包含一个我想模拟的私有方法,称为methodIWantToMock(String x)。在我的测试代码中,我正在执行以下操作:

@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassOfInterest.class)
public class ClassOfInterestTest {

  @Test
  public void someTestMethod() {

  ClassOfInterest coiSpy = PowerMockito.spy(new ClassOfInterest());

  PowerMockito.doReturn(null).when(coiSpy, "methodIWantToMock", any(String.class));

  coiSpy.methodUsingThePrivateMethod();

  //Do some stuff ...

  }
}
Run Code Online (Sandbox Code Playgroud)

根据上面的代码,当我运行上面的测试时,只要methodIWantToMock在内部调用PowerMockito 就应该简单地返回 null。methodUsingThePrivateMethod()然而,实际发生的情况是,当运行此命令时:PowerMockito.doReturn(...).when(...)PowerMockito实际上正在调用methodIWantToMock为什么要这样做?在这个阶段,我只想指定一旦该行运行时最终coiSpy.methodUsingThePrivateMethod();调用私有方法,它应该如何模拟私有方法。

Ahm*_*mad 3

所以我想出了一个适合我的解决方案。spy我没有使用 a ,而是使用了 a ,然后告诉 PowerMockito在模拟对象内部调用mock时调用真正的方法。methodUsingThePrivateMethod()它本质上做与以前相同的事情,但只是使用 amock而不是 a spy。这样,PowerMockito 最终不会调用我试图使用PowerMockito.doReturn(...).when(...). 这是我修改后的测试代码。我更改/添加的行已标记:

@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassOfInterest.class)
public class ClassOfInterestTest {

  @Test
  public void someTestMethod() {

  //Line changed:
  ClassOfInterest coiMock = PowerMockito.mock(new ClassOfInterest());

  //Line changed:
  PowerMockito.doReturn(null).when(coiMock, "methodIWantToMock", any(String.class));

  //Line added:
  PowerMockito.when(coiMock.methodUsingThePrivateMethod()).thenCallRealMethod();

  coiSpy.methodUsingThePrivateMethod();

  //Do some stuff ...

  }
}
Run Code Online (Sandbox Code Playgroud)