Vadim’s Weblog

Never stop learning.

Testing internals members with InternalsVisibleTo attribute.

Posted by Vadim on December 9, 2007

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

4 Responses to “Testing internals members with InternalsVisibleTo attribute.”

  1. Omer Mor said

    You can actually use this attribute with unsigned assemblies as well.
    There is one (undocumented) pitfall you should be aware of:
    You can’t have the following attributes in your assemblies:

    [assembly: AssemblyDelaySign(false)]
    [assembly: AssemblyKeyFile("")]
    [assembly: AssemblyKeyName("")]

    Those were used to be included by default in the AssemblyInfo.cs by VS2003. You just need to remove them in order to use the InternalsVisibleTo attribute (called friend assemblies).

  2. vkreynin said

    Omer,
    I don’t think that you can use InternalsVisibleTo attribute without strong-named assembly. Microsoft documentation specifically says: “This attribute can only be applied to strong-named assemblies”.

  3. mcgurk said

    Anybody try this with delay signed assemblies?

  4. Omer Mor said

    Vadim,
    I know that it goes against the documentation, but I can assure you it works.

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>