Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerMockito verify private method called x times

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?

like image 640
Kousha Avatar asked Jan 30 '18 02:01

Kousha


People also ask

How do you verify a private method is called in Mockito?

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.

Can we mock private methods using PowerMockito?

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.

How do you test private methods?

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.


1 Answers

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.

like image 184
pvpkiran Avatar answered Sep 18 '22 19:09

pvpkiran