Wednesday, April 9, 2014

Testing Internal Classes in .Net - Pragmatically

Lately, I've been working on a very large .Net API that our company is developing. Ultimately, the number of classes exposed to the user is very few.  To facilitate testing everything was originally developed as a public class.  Now that the development has slowed substantially, I've gone back through the code and used the Internal (C#) or Friend (VB) access modifier to hide away the code that doesn't concern the public API.

This immediately caused our automatic test runner tool NCrunch, to show failing tests.  The reason is obvious, once you change the access modifier to Internal, your test project which is a separate assembly can't see those classes.  A quick search of the internet turned up a few interesting solutions.  Some people suggested moving all the tests for the internal classes into the main assembly, marking the tests as internal as well.  I'm not a fan of that idea, as I like the separation offered by a test project. 

Other folks feel that if the class is internal, you should forget about testing it, and just test what is exposed.  Perhaps if this was a small uncomplicated API this would be okay.  However, our API is related to some fairly complex engineering tasks, and as such the internal members really need testing.  

The pragmatic solution is this...  In the project AssemblyInfo file add an attribute to expose the internal classes to your testing assembly.  

Example given here is with VB attributes...

'Exposing the assemblies to Test Framework, and to Moq's Proxy Generating Assembly
<Assembly: InternalsVisibleTo("KNE.TubingForces.BLL.Test")> 
<Assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")>
Notice that I also expose to DynamicProxyGenAssembly2, this is so Moq's proxy engine can still create mocks for internal classes as well.     

No comments:

Post a Comment