Testing Private and Protected Methods in .NET
posted on Friday, September 30, 2005 7:11 PM
by
kfinley
With Test Driven Development a question that is often raised is where should your unit tests live. Should Unit Tests be located in a separate assembly (project) or in the same project as the code being tested? There is really two sides on this topic. One side says you keep the Unit Tests in the same project as the code being tested and use conditional compilation to exclude the tests from release build. The other side says you should create tests in a separate project. This follows the rule of keeping your test independent from the code that it is testing. Often people disagree with this stating that if you create tests in a separate project you can't test private and protected methods and properties. This is not true at all. You can test private and protected methods you just have to be a little smarter about how you do it.
Now let's look around and see how other people are tackling this decision. I use many resources to help determine Best Practices in Software Development. One of these resources is Microsoft's Patterns & Practices group. If you follow their contributions to the development community you know about theEnterprise Library. In the EntLib version 1.x you will find that all the unit tests are located within each individual project. Since the release of version 1 the team has decided to drastically change their minds and jump to the other school of thought. Scott Densmore has stated that for version 2 of the EntLib all the tests will be moved to their own assembly. In that post he mentioned something that concerned me a little. He said as a result of moving the unit tests to their own project it "means we have to make some of the classes / methods / properties public that we might not normally." I have not looked into the v2 preview of the EntLib, available on the community site, much but I'm curious to see how drastic this impacted encapsulation of the various classes being tested.
My question to Scott would be why should open up access modifiers for methods on the classes being tested anyways? If you follow the techniques described byTim Stall in his article Testing Private and Protected Methods in .NET you should be able to develop unit tests with coverage to all the methods without exposing private and protected member. I've only recently started writing my tests in this manor but moving forward I'm going to try to follow this style with all my unit tests.