【问题标题】:PowerMockito is calling the method when I use doReturn(..).when(....)当我使用 doReturn(..).when(..) 时,PowerMockito 正在调用该方法
【发布时间】:2016-07-01 23:42:51
【问题描述】:

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

我有一个类,其中包含一个我想模拟的私有方法,称为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 就应该简单地返回一个空值。然而实际发生的是,当运行此命令时:PowerMockito.doReturn(...).when(...)PowerMockito 实际上正在调用methodIWantToMock 为什么要这样做?在这个阶段,我只想指定在运行coiSpy.methodUsingThePrivateMethod(); 行时最终调用私有方法后如何模拟私有方法。

【问题讨论】:

  • 您在模拟对象上调用methodUsingThePrivateMethod(),而后者又在内部调用methodIWantToMock("some string")。您在这里期待什么行为?
  • 没错,但是通过调试我发现当我运行doReturn().when() 命令时,PowerMockito 调用了methodIWantToMock()。它不会等待methodUsingThePrivateMethod() 调用它。
  • 我通过调试发现了这种行为。如果我运行测试(没有调试),测试会因为生成NullPointerException 而崩溃,因为当执行doReturn(...).when(...) 命令时,PowerMockito 运行私有方法同时将null 作为输入传递,所以当String y = x.trim();methodUsingThePrivateMethod() 内部执行,会生成一个NullPointerException。底线 === 命令 coiSpy.methodUsingThePrivateMethod(); 永远不会被调用。

标签: java mockito powermockito


【解决方案1】:

所以我想出了一个适合我的解决方案。我没有使用spy,而是使用mock,然后在我的模拟对象中调用methodUsingThePrivateMethod() 时告诉PowerMockito 调用真实方法。它基本上和以前做同样的事情,但只是使用mock 而不是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 ...

  }
}

【讨论】:

  • 对于这一行:PowerMockito.doReturn(null).when(coiMock, "methodIWantToMock", any(String.class)); // coiMock 不能调用methodIWantToMock,对吧?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-11
  • 1970-01-01
  • 1970-01-01
  • 2023-03-12
  • 1970-01-01
相关资源
最近更新 更多