Unit Testing private methods in C#

Unit Testing private methods in C#

-“Should private methods in C# be Unit Tested?”


Short answer:

No, they shouldn’t.


Long answer:

Generally you don’t write unit tests for private methods since they are not accessed from outside the implementation class (private methods are considered implementation detail)

Since they are most likely part of or called from within another non-private method (in that same class), the private logic will be tested as part of that non-private logic. This is also why most Test Coverage Tools don’t tend to scan private methods when calculating test coverage percentage. 

If you find that your private method is very complex and would require its own unit testing, but you don't want it to be publicly accessed, I would advise switching to an internal access modifier and use the [InternalsVisibleTo] attribute to access your private method in your unit test project. I wrote an article on this subject a while back:

Ps. there might be some voodoo magic or package out there allowing you to write unit tests on private methods but I would avoid it.

Cheers friends! ❤️