Matt Brunell
Matt Brunell

Reputation: 10389

How can I mock an internal interface using NMock2?

If I try this, I just get an exception:

System.TypeLoadException : Access is denied: 'Namespace.IInternalInterface'.

Making the interface public is not an acceptable solution. I don't want to change the visiblity of my API in order to test it.

Upvotes: 0

Views: 913

Answers (2)

Rhyous
Rhyous

Reputation: 6690

Found and documented the solution.

http://www.rhyous.com/2012/05/03/nmock2-internal-interface/

Turns out that the newer version of NMock2 (I got it here: NMock2 Project) only needs one and it is different.

[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]

Upvotes: 3

Matt Brunell
Matt Brunell

Reputation: 10389

I found the answer to this:

NMock2, (and other mocking frameworks). Will create the mock objects in dynamically generated assemblies. In order for the mocking framework to create the mock object, the internals should be visible to these assemblies.

Just add the following declarations to the AssemblyInfo.cs class for the Module Under Test:

// Allow unit test and mock assemblies to see internal members.
[assembly: InternalsVisibleTo("MyAssembly.UnitTest")]
[assembly: InternalsVisibleTo("NMock2")]
[assembly: InternalsVisibleTo("Mocks")]
[assembly: InternalsVisibleTo("MockObjects")]

Upvotes: 2

Related Questions