Unit testing internal methods
August 2, 2010 | In Development |When unit testing applications you write tests for the exposed public methods. Philosophically this is correct as you need to test the functionality exposed by your class to the consuming application, and any private or internal functions that use functionality that also needs testing should be discrete from this class. This functionality should be ‘injected’ into the class using some form of unit-testable framework; such as dependency injection using interfaces, allowing them to be tested separately.
However, there are occasions when you want to hide methods from external consumers for good reason, but still need to unit test them. For example, producing a library to distribute to third-parties.
To do this with .NET you can mark the assembly with InternalsVisibleTo and specifiy the public key of the project allowed to view your internals.
For example, I have a project called MyNewProject and a project containing units tests for this called MyNewProjectTests, I can add the following code to the assembly.cs file in MyNewProject with the public key of the test project:
[assembly: InternalsVisibleTo("MyNewProject, PublicKey=0024...")]
Note, I’ve not included the entire public key here.
Now the internal methods are visible to the test project we have one more task. The unit test frameworks Rhino Mocks and Moq use a proxy class called DynamicProxyGenAssembly2 to represent your object when testing. We therefore need to expose the internals to this class also. We do this in the same way with another entry in the assembly.cs file:
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2, PublicKey=0024")]