.NET by Kurt

Internal Visible To

In the .Net Framework, the approach to unit testing internal methods or types was to add an InternalsVisibleTo attribute into the AssemblyInfo.cs file. For example, look at the following line of code below:

InternalsVisibleTo Attribute

[assembly: InternalsVisibleTo("Projects.Tests")]

This all works fine in the .net Framework. However, in .Net Core, most of the settings in the AssemblyInfo file have been moved to the project file. So, to test internal methods, you have two options.

Project File Change

Assuming we have a project called Projects and a unit test project called Projects.Tests. The Projects project file, which contains the internal method, can be modified in Visual Studio with the following:

AssemblyAttribute

<ItemGroup>
    <AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">
        <_Parameter1>Projects.Tests</_Parameter1>
    </AssemblyAttribute>
</ItemGroup>

Starting with .NET 5, you can use the <InternalsVisibleTo> without adding any NuGet package:

<ItemGroup>
    <InternalsVisibleTo Include="Projects.Tests" />
</ItemGroup>

Source File change

The alternative way is to use an attribute in the source file containing the internal method. For example, see the code below:

using System.Runtime.CompilerServices;

[assembly: InternalsVisibleTo("Projects.Test")]

namespace Projects
{
    public class User
    {
        internal string Hello(string username)
        {
            return $"Hello {username}";
        }
    }
}

Additional Resources:

Comments