Tuesday, March 11, 2008

Testing Internal Class in .Net C#

I have been to a situation where only a small number of classes had been declared as public classes in an assembly. And most of the classes are declared as internal, because I wanted to expose only the public classes to the consumers of my assembly.

However, doing so creates another challenge in testing the internal classes. As we most commonly want our test codes to reside on a separate assembly so that we can leave that assembly out when we are releasing the end product. And the internal access control would makes it difficult to write unit tests for these classes.

One workaround to this problem is to keep the test classes in the same assembly so that the test class has access to the internal class. However, to leave out these test classes from release configurations, we need to apply a conditional compilation for these files.

However, this is a pessimistic or short cut solution to the real problem. We actually want to test an internal class from another assembly (the test assembly) and don't want to go through reflection or other less intuitive paths.

I just found that, adding the following assembly attribute in the AssemblyInfo.cs may do the trick.

[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("TestAssemblyName")]

Adding this attribute will make the assembly's internals visible to the assembly thats specified in the argument.

So, once this attribute is added to an assembly, the test assembly treats the internal classes just as other public ones and need not worry about access protection problems.