Sunday, March 16, 2008

Mock Internal Interface with NMock2 - Use InternalsVisibleToAttribute

Yesterday I badly needed to create mocks for my internal interfaces. I am using NMock2 as a Mocking framework and found it really difficult to produce Mocks for internal interfaces. After some 'google time' and investigation I found that you need the following two lines in your AssemblyInfo.cs to achieve this purpose-

[assembly: InternalsVisibleTo("Mocks")]
[assembly: InternalsVisibleTo("MockObjects")]

Where are the two assemblies? I found that these two assemblies are dynamically created by NMock2 for mocking your interfaces.

To find out the truth yourself, just put a breakpoint and watch the value of the following line-

AppDomain.CurrentDomain.GetAssemblies()

You should see the two assemblies in the list of the assemblies in the current application domain.

I found it interesting. I wish someone of you might find it useful too!

Note: You may still need to add InternalsVisibleTo attribute for your test assembly with the above two declarations.