Should I cover private methods in unit tests?

1

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

I do not know if this is the most correct route. Should I test my private methods? All?

In .NET, the InternalsVisibleTo attribute % enables this, which left me with this doubt (although the question is not limited to this framework )

    
asked by anonymous 01.11.2017 / 17:23

2 answers

1

In general, it should not. Properly used private methods are implementation details and the purpose of unit testing is to test the public API rather than the detail.

The private method is just an aid to public methods, so no matter what changes in it or if it is giving the correct result, it matters whether audiences are giving the correct result. If the private is wrong the public will surely be wrong, and it is he who can not go wrong.

The unit test does not have to show where the error is, just that there is an error when using the API as expected, or that the usage unexpectedly is not properly handled.

For everything there is an exception and there are cases that you can do this, just not the normal one. So much that there is controversy about this. You can see in the answers in the OS that the most voted say opposite things . I would say that testing the private is something that goes beyond the unit test, but can be done as a form of extra protection and give more subsidies for testing.

.NET provides the means to work with "all" styles. InternalsVisibleTo is not just for this.

01.11.2017 / 17:34
1

In principle it should not be necessary to test them.

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

So it 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.

    
01.11.2017 / 17:34