Blog Archive

Tuesday, June 27

Testing internal code

A few upfront assertions:

  1. Unit testing is good. For C# code I use NUnit (along with TestDriven.NET).
  2. Languages (including C#) have been designed with the internal keyword for a reason. There are legitimate uses for something that's accessible only within one's own assembly.
  3. These internal classes/methods are reasonable candidates for unit testing.

So, how do you test internal bits without compiling test code into your deliverable assembly?

It turns out that it's trivial (in the .NET 2.0 Framework): Friend Assemblies (see also).

Say you have two projects: MyCoolAssembly and MyCoolAssembly.UnitTests.

  1. In your MyCoolAssembly, open up the Properties/AssemblyInfo.cs.
  2. Add [assembly: InternalsVisibleTo("MyCoolAssembly.UnitTests")]

That's it! Now, MyCoolAssembly.UnitTests can access all of the internal classes/methods within MyCoolAssembly.

No conditional compilation symbols. No messy inner classes. Problem solved.

I found out about this useful attribute in CLR via C#, but Jay Bazuzi (whose blog I'd really like to read except that he apparently doesn't post anymore) had already blogged about this very usage back in September of 2004.

2 comments:

Anonymous said...

The problem with InternalsVisibleTo is that you immediately loose the "consumer perspective" on the code you're testing. I think this is an important benefit of doing test driven development.

I guess one possibility would be to have a separate test assembly for testing internal types. I can't however see myself doing it this way. I find my solutions quickly balloon even with one test assembly per test target (for testing public types).

I'm still looking for a good solution to this problem!

Jacob said...

You know, I hadn't considered that the entire test assembly now becomes somewhat "omniscient". That's a good point.