InternalsVisibleTo with strong-named assemblies

  • .NET
  • Tools

The InternalsVisibleTo attribute is a well-known attribute for testing assemblies. The internal methods of an assembly become visible to the test project. This allows you to test the internal methods without using reflection, so your tests are more maintainable.

If the assembly does not have a strong name, you can easily add the InternalsVisibleTo attribute:

// Project
[assembly: InternalsVisibleTo("TestProject")] // The TestPrject will have access to the internal types and members

public static class Sample
    internal void Fibonacci(int n)
        // TODO

// Testproject
public class Test
    public void TestFibo()
        Sample.Fibonacci(0); // No error

However, if the assembly has a strong name, the name of the assembly must include the PublicKey. Getting the PublicKey, not the PublicKeyToken, is not very convenient. As I don't want to remember the procedure, here's the steps.

I suppose you already have a snk file

  1. Find sn.exe in the Windows SDK (C:\Program Files\Microsoft SDKs\Windows\v6.0A\Bin)
  2. Extract the public key of the snk file
sn.exe -p file.snk file.PublicKey
  1. Get the readable version of the public key
sn.exe -tp SomeName.PublicKey

It shoud print a long sequence of digits and letters in the console.

  1. Copy the public key in the InternalsVisibleTo:
[assembly: InternalsVisibleTo("ProjectTest, PublicKey=002400000...")]

If you do not copy the expected public key, you'll get a compilation error.

Do you have a question or a suggestion about this post? Contact me on Twitter or by email!

Follow me:
Enjoy this blog?Buy Me A CoffeeDonate with PayPal