Unit Testing and accessing Internal members

I’ve recently been doing reading related to unit testing, or more particularly, test driven development and so I’ve been working hard to learn how to write effective unit tests.

In my fervour, I ran across an issue that had me stumped for a couple of weeks.  My goal was to put all my unit tests in a separate assembly so that when it comes time to ship there was a clean separation of the functional and test code.  The problem was I was also trying to limit the public surface of my code to the bare minimum, marking classes and methods as Friend (or Internal in C#).  This made much of the code I wanted to unit test inaccessible.

Fortunately Microsoft had anticipated this problem and created an assembly attribute called InternalsVisibleTo to the framework.  This makes it possible to make the Friend/Internal members accessible to a specified “friend assembly” (i.e. your unit test assembly).  This worked great until I tried to strong sign my assemblies.

The Microsoft documentation says that you need to supply the full public key of the “friend assembly”.  However I didn’t know how to obtain the public key of the assembly without compiling it first, but you can’t compile it because the Friend/Internal members aren’t visible to your test code.

Fortunately I ran across this blog post which described how to obtain the public key from the snk file. Basically you use the sn.exe utility to extract the public key from the snk file to a temporary file (I couldn’t see how to do this in one step either) using:

sn.exe -p your_key_file.snk temp_file.public_key

Then convert the public key into a hex string using:

sn.exe -tp temp_file.public_key

As a follow up to this, the same method works for password protected signing files (pfx files) you just get a prompt to enter the password as well.

Now I just need to figure out how to automate this process…