I was running a technical session on TDD today. Whilst I was doing my research into ways to work with private members I discovered a new way. The C# language has evolved and the tools in Visual Studio have improved providing new ways to solve old problems. You can now solve the private member problem the following ways:
I won't go into the first few too much as I believe the last one supersedes them.
#if DEBUG or TESTYou can surround your public accesses to your private members inside compiler directives so they only get built when you build you unit tests.
Internal members and internal visible toMake your private members internal rather than private and then use the InternalsVisibleTo attribute to make them visible to your tests. (new to .net 2)
Partial classesYou can put your unit tests in a partial class and exclude this class when you build the release code (new to .net 2)
Create a private accessorThis is a feature which is new in VS2008. You can see this working as follows:
- Create a new Class Library project
- Add a private member to Class1 (the generated one)
string nottelling = "my tests cannot access me";
- Add a test project
public void Test()
var class1 = new Class1_Accessor();
Assert.AreEqual(class1.nottelling, "my tests cannot access me");
Old Problems may have different solutions using newer tools, you should always keep looking for new ways to solve old problems