InternalsVisibleTo with strong-named assemblies

 
 
  • Gérald Barré

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:

C#
// 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
[TestClass]
public class Test
{
    [TestMethod]
    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

    Shell
    sn.exe -p file.snk file.PublicKey
  3. Get the readable version of the public key

    Shell
    sn.exe -tp SomeName.PublicKey

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

  4. Copy the public key in the InternalsVisibleTo:

    C#
    [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!

Follow me:
Enjoy this blog?Buy Me A Coffee💖 Sponsor on GitHub