Testing Internal Classes and Methods

By fango256

I’m really starting to get the hang of this TDD approach now but I thought I came a cropper the other day when I couldn’t find a way of testing an internal class.  I’m using the VSTS in-built testing technology (similar to NUnit) and when using these frameworks your tests would sit in another assembly (you wouldn’t want to ship your tests in most cases).

Now I personally don’t see the advantage of testing private methods as their workings will always have an impact on the public methods, with not too many levels of indirection.  However an internal class is a different thing altogether, it could be a complex piece of functionality that gets used in multiple places inside an assembly. 

Thankfully the .NET guys have realised this to so have given us a command like the ‘friend’ command in C++ to allow a whole other assembly to get access to the internal workings.  Personally I actually think the C++ approach is more robust as it only grants an individual class access but at least it’s a solution.  Maybe the .NET guys wanted it to be clear this attribute was only used for testing assemblies and not for messy its internal to X but not Y scenario’s.

Simply add this line into your AssemblyInfo.cs:

[assembly: InternalsVisibleTo("YourTestAssembly")]

Leave a Reply