Should I cover private methods in unit testing?

Asked

Viewed 441 times

2

In my unit testing coverage, private functions are not tested.

I don’t know if this is the right route. Should I test my private methods? All?

No. NET, the attribute InternalsVisibleTo makes it possible, which left me with this doubt (although the question is not limited to this framework)

2 answers

4


Generally speaking, you shouldn’t. Private methods used properly are implementation details and the goal of unit testing is to test the public API rather than the detail.

The private method is just an aid to public methods, so it doesn’t matter what changes in it or whether it’s giving the right result, it matters whether audiences are giving the right result. If the private is wrong the public will surely be wrong, and it is he who cannot be wrong.

Unit testing does not have to show where the error is, only that there is an error when using the API as expected, or that unexpected use is not properly handled.

For everything has exception and there are cases that you can do this, only it is not normal. So much so that there are controversies. You can see in answers in the OS that the most voted things say opposite things. I would say testing the private is something that goes beyond unit testing, but can be done as extra protection and give more subsidies to the test.

The . NET provides means to work with "all" styles. The InternalsVisibleTo not only for this purpose.

3

In principle it should not be necessary to test them.

A private method, if it exists, is to be called.

This will be used directly or indirectly by a public method.

If the tests you implement cover all public methods, then private methods are also covered.

Browser other questions tagged

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