PowerMockito验证称为x次的私有方法

Kou*_*sha 6 java junit powermock powermockito

我正在使用PowerMockitospy模拟私有方法:

final SomeClass someClass = new SomeClass();
final SomeClass spy = PowerMockito.spy(someClass);

PowerMickito.doReturn("someValue", spy, "privateMethod1");
final String response = Whitebox.invokeMethod(spy, "anotherPrivateMethod");

// I can now verify `response` is of the correct data
// But I also want to verify `privateMethod1` was called x times or so
Run Code Online (Sandbox Code Playgroud)

我无法弄清楚如何验证我的方法被调用了x次。

边注

仅仅制作我的所有私有方法protected,然后在测试类中扩展该类并做到这一点会更好吗?

pvp*_*ran 10

这会做。

PowerMockito.doReturn("someValue", spy, "privateMethod1");
final String response = Whitebox.invokeMethod(spy, "anotherPrivateMethod");
assert(response)
verifyPrivate(spy, times(1)).invoke("anotherPrivateMethod", "xyz");
Run Code Online (Sandbox Code Playgroud)

我假设您的私有方法(anotherPrivateMethod)采用一个参数“xyz”。您可以根据您的私有方法声明进行修改。

  • 我仍然想验证调用方法的响应。我如何从您的示例中获得调用的结果? (2认同)