Search code examples
reflectionmockitopowermockpowermockito

How can we mock private methods without using power mockito


Can we mock private methods without using powermockito. I know it is possible though powermockito but just wanted to check with all, is it possible by some other means. Thanks -Sam


Solution

  • By design, this isn't possible without PowerMockito or a similar tool.

    See Mockito's Wiki where they give the following reasons:

    1. It requires hacking of classloaders that is never bullet proof and it changes the API (you must use custom test runner, annotate the class, etc.).

    2. It is very easy to work around - just change the visibility of method from private to package-protected (or protected).

    3. It requires the team to spend time implementing & maintaining it. And it does not make sense given point (2) and a fact that it is already implemented in different tool (powermock).

    4. Finally... Mocking private methods is a hint that there is something wrong with Object Oriented understanding. In OO you want objects (or roles) to collaborate, not methods. Forget about pascal & procedural code. Think in objects.

    There are of course cases where it is not possible to work around, but just take a step back and

    1. Make sure that you are testing the correct things (should you be testing private methods instead of the public ones)
    2. Consider just changing these methods to be package private instead of relying on PowerMock.