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

PowerMockito is calling the method when I use doReturn(..).when(....)

我是 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 ...
  }
}

我有一个 class,其中包含一个我想模拟的名为 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 ...

  }
}

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

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

@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 ...

  }
}