PowerMockito verify private method called x times

Kousha picture Kousha · Jan 30, 2018 · Viewed 12.2k times · Source

I'm using PowerMockito and spy to mock private methods:

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

I cannot figure out how to verify that my method was called x times.

Side note

Is it better to just make all my private methods protected and then extend that class in my test class and do that?

Answer

pvpkiran picture pvpkiran · Jan 30, 2018

This will do.

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

I am assuming your private method(anotherPrivateMethod) takes one argument "xyz". Which you can modify according to your private method declaration.