Use of InternalsVisibleToAttribute

December 23, 2015 0 By Manish Kumar

Suppose we have a C# project and a test project with unit tests for the main project. We want to have testable internal methods and test them without a magical Accessor object that we can have with Visual Studio test projects. Usually developers are doing this by creating key files for signing the assemblies and then using sn.exe to get the public key and so on.

We can achieve this without signed assembly, there are couple of ways to do this:

Option 1: Using “InternalVisibleToAttribute”

I assume my project name is ‘MyAssembly‘ and test project name is ‘MyAssembly.Test’. If we want to have access to MyAssembly in our test assembly  (MyAssembly.Test), we need to add the name of the test assembly in ‘AssemblyInfo.cs’ of MyAssembly project like this:

[assembly: InternalsVisibleTo("CompanyName.Project.MyAssembly.Test")]

Option 2: There is another way call internal methods and that is using “Reflection”.

 BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.NonPublic;
 MethodInfo minfo = typeof(BaseClassName).GetMethod("MethodName", bindingFlags);
 BaseClassName b = new BaseClassName();            
 minfo.Invoke(b, null);

Here I assumes that “BaseClassName” is name of the class from another classlibrary and “MethodName” is name of internal method.