Jun 7, 2010

Unit testing internal methods in a strongly named assembly/project

If you need create Unit tests for internal methods within a assembly in Visual Studio 2005 or greater, then we need to add an entry in the AssemblyInfo.cs file of the assembly for which you are creating the units tests for. For e.g. if you need to create tests for a assembly named FincadFunctions.dll & this assembly contains internal/friend methods within which need to write unit tests for then we add a entry in the FincadFunctions.dll’s AssemblyInfo.cs file like so :

[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("FincadFunctionsTests")]

where FincadFunctionsTests is the name of the Unit Test project which contains the Unit Tests. However if the fincadFunctions.dll is a strongly named assembly then you will the following error when compiling the FincadFunctions.dll assembly :


Friend assembly reference “FincadFunctionsTests” is invalid. Strong-name assemblies must specify a public key in their InternalsVisibleTo declarations.

Thus to add a public key token to InternalsVisibleTo Declarations do the following: You need the .snk file that was used to strong-name the FincadFunctions.dll assembly. You can extract the public key from this .snk with the sn.exe tool from the .NET SDK. First we extract just the public key from the key pair (.snk) file into another .snk file. sn -p test.snk test.pub Then we ask for the value of that public key (note we need the long hex key not the short public key token): sn -tp test.pub We end up getting a super LONG string of hex, but that's just what we want, the public key value of this key pair. We add it to the strongly named project "FincadFunctions.dll" that we want to expose our internals from. Before what looked like:

[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("FincadFunctionsTests")]

Now looks like.

[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("FincadFunctionsTests, PublicKey=002400000480000094000000060200000024000052534131000400000100010011fdf2e48bb")]

And we're done. hope this helps

kick it on DotNetKicks.com

No comments: