The opinions vary on this subject, so I'll say it depends. Those who oppose testing private methods, claim that you should only test the public API. This makes a certain sense, as testing private methods will usually lead to testing implementation, while unit tests should test behavior and if that code needs to be tested then there's a code smell and a design problem. Also by testing public API you indirectly already test the private method - that's also what encapsulation is for. The private testing proponents claim that you should test as much logic as possible and if there's a reason to test a private method you should. I believe that good design would usually reduce the need for testing private methods, but there are still some reasons for testing private methods. Let's not forget that there's also a lot of legacy code that wasn't designed to be testable, so testing private methods would make more sense in order to refactor that code. Problem with that is how to test private methods, as mocking is usually limited to public and virtual methods unless you use "unlimited" mocking tools. So you should decide what is the right path for you or your team, just be consistent.
GregoryPres
Posts
-
Should I unit test private methods? -
What is the best way to practice unit testing in C#?I would also suggest reading on some unit test patterns.
-
Which unit testing tools are integrated with Visual Studio?Most unit test tools that are designed to work with VS are integrated to a certain degree. It can be full integration like ReSharper, NCrunch, Typemock Isoaltor. And it can be an integration through adapter (easily downloadable via NuGet) as in NUnit, xUnit. What usually separates full and "partial" integration is the price as you can see.
-
Do you know any good unit testing and mocking frameworks for C#?I usually use NUnit for test running, though we are thinking about porting to XUnit. For mocking we use Typemock as we need to deal with some legacy code. You can use Moq as well if you're starting a new project or if your code is testable. I've used it before when we were employing TDD from the beginning.
-
“Unit” tests?I recall Uncle Bob saying the term "unit" is unfortunate as some might look at classes as units. Some might even look at every method as a unit even non-public ones (in the pursuit of 100% coverage maybe?). At my workplace, we define a "unit" as a behavior. It might be one method, or one method using several auxiliary methods or even one class depends on its size and usage.