17

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?

Kousha
  • 32,871
  • 51
  • 172
  • 296

2 Answers2

13

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.

pvpkiran
  • 25,582
  • 8
  • 87
  • 134
  • 1
    I still want to validate the response from the invoked method. How would I get the result of the invoke from your example? – Kousha Jan 30 '18 at 08:26
-3

Testing private methods is testing implementation details. If you choose to change the implementation the tests become worthless and will be thrown away.

You should strive to test the What, not the How. Then the tests will survive even if you change implementation.

A wonderful paper on how to avoid testing incidental details can be found here.

Frank Neblung
  • 3,047
  • 17
  • 34