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?
For Mockito, there is no direct support to mock private and static methods. In order to test private methods, you will need to refactor the code to change the access to protected (or package) and you will have to avoid static/final methods.
PowerMock integrates with mocking frameworks like EasyMock and Mockito and is meant to add additional functionality to these – such as mocking private methods, final classes, and final methods, etc. It does that by relying on bytecode manipulation and an entirely separate classloader.
To test private methods, you just need to test the public methods that call them. Call your public method and make assertions about the result or the state of the object. If the tests pass, you know your private methods are working correctly.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With