Tag Archives: Unit testing - Page 2

Signing a Project and InternalsVisibleTo – Extract a Public Key for the Unit Test Project

I recently completed a project and went to give it a strong name by signing it, when an interesting thing happened. It didn’t compile anymore. The relevant error message was Friend assembly reference ‘WinFormsMvp.UnitTests’ is invalid. Strong-name signed assemblies must specify a public key in their InternalsVisibleTo declarations.
Upon investigation, I discovered what was going on.

One of my unit tests needed access to the internals of a class in my project i.e. I had a class with the protection level of internal being exposed to my unit tests. This was done using the following line of code in the AssemblyInfo class:

[assembly: InternalsVisibleTo("WinFormsMvp.UnitTests")]

However, when I signed the project, the solution wouldn’t build because the Unit Test project also needs to be signed. A strong-named assembly can only reference strong-named assemblies.

So, the solution:

  1. create a separate strong-name key for the unit test project:
    sn -k WinformsMVPTestsKey.snk
  2. extract the public key for the key you just created (prepare yourself for a big string):
    sn –tp WinformsMVPTestsKey.snk
  3. add the extra detail into the line of the AssemblyInfo class described above, assigning the public key string to the PublicKey value:
[assembly: InternalsVisibleTo("WinFormsMvp.UnitTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100eb6fea45976e16daadfd3f49c17d7d8abec952b6acd435ceb9ea24efdcfe7b2a2a528f04a6a8269ee88a2cf4b839668a11a580caeab03762abf968cff05d0107c786dc5b7d9d97b14a13277df132222350ad4dc1dd24c03b1d10db168066fbe8ddf3f49b04b6248264479d21bfdabd79b68291da2d62a5ab17fc55819869a4e9")]

That’s how it’s done!