Test private methods in C# .Net

I was writing Unit Tests for a module that has many private methods.

With these tricks, my UnitTest assembly is allowed to access all methods and properties as if they were declared Internal, rather than private, without changing the production code modifiers to internal.

When creating the Unit Tests, Visual Studio 2008 suggested I added the following line to AssemblyInfo.cs on the Target assembly under test.

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

However, I got the following error during build time:

Friend assembly 'UnitTests' reference is invalid.
 Strong-name signed assemblies must specify a public key in their InternalsVisibleTo declarations

To fix this, make sure your UnitTest assembly is signed. (As detailed in this MSDN Article)

Use SecUtil to find your public key’s token in Hex.

secutil.exe -hex -s UnitTests.dll

SecUtil comes with the Microsoft SDK.

I didn’t want to use the command line, because it requires knowing and typing the full path to the DLL file, so I added SecUtil to my External Tools in visual studio, to keep it handy.

image

SecUtil as External Tool in Visual Studio 2008

Add the PublicKey value without 0x prefix, like this:

[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("UnitTests,PublicKey=002.....1093")]

Now build and observe the Errors and Warnings are gone.

This entry was posted in C# and tagged , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*