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

时间:2018-01-30 02:40:30

标签: 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

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

旁注

最好只创建我的所有私有方法protected,然后在我的测试类中扩展该类并执行此操作吗?

2 个答案:

答案 0 :(得分:2)

这样做。

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

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

答案 1 :(得分:0)

测试私有方法正在测试实现细节。 如果您选择更改实施,则测试将变得毫无价值,并且将被丢弃。

你应该努力测试什么,而不是如何。然后,即使您更改实施,测试也将继续存在。

可以找到关于如何避免测试附带细节的精彩论文here

相关问题