Unit Testing Internal Code

While presenting yesterday at the MSDN Event in Mountain View I was asked by someone how you go about unit testing internal code.

We'll use the open source CodePlex.Diagnostics framework that I wrote to illustrate how this can be achieved.

Within a C# project you have types that are marked as internal and then within a separate C# unit test project you'd like to write unit tests that ensure the internal types are written correctly. But wait, if these types are internal how can you access them within the unit test project?

One option would be to use reflection to ignore the internal visibility of the types from within the unit test code although that involves writing complicated code unnecessarily. Instead you right click on the unit test project and select the Add Existing Item option.


Within the dialog that appears you'll notice that there is an Add As Link option. Simply navigate the file system to the internal type within the original C# project and add it to the unit test project as a linked item.

Once the item is added into the unit test project as a linked item you'll see the icon for the file within the unit test project has a small arrow overlayed on top.

The internal code will then exist only once on disk and even only once within source control systems although it is shared within two or more projects. If the file is under source control then checking the file out from any project it is contained within will result in it being checked out anywhere it exists within your solution guaranteeing also that the code is kept synchronized within the main assemblies and unit test assemblies.

Einzelheiten zur Compiler-Optimierung finden Sie in unserem Optimierungshinweis.