.Net, Coding, TDD

Testing internals members with InternalsVisibleTo attribute.

I posted previously about testing non-public members with MbUnit.  I recently found out about InternalsVisibleTo attribute by reading Roy Osherove‘s book The Art of Unit Testing.

To use this attribute, your test assembly must be strong-named.  Then you put InternalsVisibleTo attribute with public key of test assembly into AssemblyInfo.cs file of assembly under test.

 1: [assembly: InternalsVisibleTo("MyAssembly.Tests, PublicKey=XXX")]

I created an Assembly Helper tool that creates the syntax for you.  The tool is working (or should work) with following languages:

  • C#AssemblyHelper
  • Visual Basic
  • Delphi
  • MS C++
  • Chrome

You can get the tool from here.

Steps to use InternalsVisibleTo attribute with the tool.

Let assume that you have Assm_A and Assm_ATests.

  1. Sign Assm_A and Assm_ATests with a Strong Name. You can read about that here.
  2. Compile your assemblies.
  3. Launch Assembly Helper tool .
  4. Select desired language and press on ‘Get Assemblies’ button and navigate to Assm_ATests.dll.
  5. Copy the text into AssemblyInfo file of Assm_A assembly.

Now your tests can access internals members of the assembly under test.

Note: With Assembly Helper tool you can select multiple assemblies at once.

kick it on DotNetKicks.com