Unit test of C# class with Internal access modifier

Edit
Have you ever encounter the situation that you need to unit test a C# class which has "Internal" as access modifier? By definition, "Internal" class can only be accessed by classes within the same assembly/namespace. And most of the time unit tests are located in another assembly. So how can we unit test the Internal Class?

Some people might just change the internal class back to a public class(That will be my last resort too). But I decided to spend more time to investigate it and I found the proper way to do it. It is the use of "InternalsVisibleTo" Attribute. Here is the usage:
using System;
using System.IO;
using System.Runtime.CompilerServices;

[assembly: InternalsVisibleTo("AssemblyA.Unit")]

public class AssemblyA
{
   internal static string AppendDirectorySeparator(string dir)
   {
      if (! dir.Trim().EndsWith(Path.DirectorySeparatorChar.ToString()))
         return dir.Trim() + Path.DirectorySeparatorChar;
      else 
         return dir;
   }
}
The scenario is that Assembly A has an internal method, and it has to be test in the unit test and the tests are located in another assembly named "AssemblyA.Unit". If we didn't use that InternalsVisibleTo attribute, Visual Studio will not build the project properly.

Hope it will help those who need to unit test internal classes in C#!

Further reading:
Friend Assemblies (C# and Visual Basic)
Unit test of C# class with Internal access modifier Unit test of C# class with Internal access modifier Reviewed by DF on 11:33:00 PM Rating: 5
©DF. Powered by Blogger.