Thursday, October 8, 2009

Private Members in Unit Tests

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.


You 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 to

Make 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 classes

You 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 accessor

This 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

  • Open class1.cs and right click on the text Class1.

  • Select Create Private Accessor -> TestProject1
  • This will create a Private Accessor in test project one.
  • Add a new Unit test and enter the following code

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

No comments:

Post a Comment