How to perform tests on private methods using Mockito

Asked

Viewed 1,739 times

1

this weekend I read about the Mockito and double tests, and I came up with the following idea. Test private methods with this framework.

I saw that the PowerMock performs such a procedure, but someone has already tried to do so using the Mockito with reflection?

In this discussion I would also like to know from friends the opinion about testing or not private methods, I saw some discussions on this in SO.com and I was in doubt, because when I declare a private method only segment for each method a responsibility and not put several things in the same method.

Thank you

  • 2

    I believe that it is not necessary to test private methods, as they exist as an aid to the public. Testing public methods should be sufficient.

1 answer

3

Apparently not possible with Mockito, but there is Powermock, a framework that extends other frameworks like Mockito, and allows test private methods.

However, in general, if a private method has any logic or algorithm sufficiently complex to require unit testing on its own, then it may be manageable to delegate responsibility to another class and then test it.

Another possibility, which sacrifices a little the design, would make the method "protected" (protected) so that other classes in the same package can access it. If there is proper division of packages in the system this is usually not a problem. So just create the test in the same package.

In fact, often the level of visibility private ends up being "strong" too much. I have seen many cases where I needed to extend a class and an important method was private, forcing me to create another class or duplicate the method.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.