Tuesday 3 March 2009

InternalsVisibleTo, C++/CLI and as_friend

We came across an interesting problem today that had an unexpected answer. The problem we had is we have an assembly we're trying to unit test. The classes we're interested in testing are internal to the assembly but implement public interfaces. We don't want to make them public just for the purposes of testing as this could lead to "accidental" use elsewhere in the code, breaking the encapsulation we're after.

We know that there is an attribute [InternalsVisibleTo] that we can apply to the assembly under test giving the test assembly permission to see the internal classes. We have done this with C# test assemblies and all is fine, but it wasn't working for our C++/CLI test assembly.

All of our assemblies are signed, so after an hour checking that all the public key tokens matched, we were stumped. Then after much Googling, we came across the "as_friend" option on the #using directive. This is the magic flag you need in the C++/CLI test assembly to allow it access to the internals of the assembly under test. There is no explaination (that I have found) in the MSDN documentation why the C++/CLI test assembly needs this and a C# one doesn't!

Now, in order to use this option you can't use the standard C++/CLI References mechanism in the project properties dialog as it ain't there. So you need to remove the reference to the assembly under test from there and use


#using "AssemblyUnderTest.dll" as_friend


in the stdafx.h file of the test assembly. This should then fix the issue.