The InternalsVisibleTo attribute is commonly used to expose internal members of an assembly to a test project. This lets you test internal methods without reflection, making your tests more maintainable.
If the assembly does not have a strong name, adding the InternalsVisibleTo attribute is straightforward:
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 InternalsVisibleTo attribute must include the PublicKey. Retrieving the PublicKey (not the PublicKeyToken) is not immediately obvious, so here are the steps.
This assumes you already have a .snk file.
Find sn.exe in the Windows SDK (C:\Program Files\Microsoft SDKs\Windows\v6.0A\Bin)
Extract the public key of the snk file
Shell
sn.exe -p file.snk file.PublicKey
Get the human-readable version of the public key
Shell
sn.exe -tp SomeName.PublicKey
This prints a long hexadecimal string to the console.
Use the public key in the InternalsVisibleTo attribute:
C#
[assembly: InternalsVisibleTo("ProjectTest, PublicKey=002400000...")]
If the public key does not match, you will get a compilation error.
Do you have a question or a suggestion about this post? Contact me!