Wednesday, January 23, 2013

Mocking an internal interface with Moq

The other day I was trying to write some unit tests on a public class with an internal constructor.  In order for the test project to get access to the internal constructor (primarily used for testing) I had to add the assembly: InternalsVisibleTo to the AssemblyInfo.cs file and specify the class library I was testing would expose its internals to the test class library, for example:

[assembly: InternalsVisibleTo("SomeApi.Test")]

This got me close, next issue was the parameter of the internal constructor was an internal interface referencing a dependency of the class under test.  No big deal.  I figured I would use Moq to mock out the dependency and I got the following error when trying to run the test:

Test method SomeNamespace.SomeClass.SomeTestMethod threw exception:
Castle.DynamicProxy.Generators.GeneratorException: Type SomeNamespace.SomeInterface is not public. Can not create proxy for types that are not accessible.

Hmm, it seems like Moq does not have access to the internals.  Adding the following to the class libraries AssemblyInfo.cs file solved the problem

[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]

Next time I ran the test Moq was able to access the internal interface and my test passed.