.Net Core – Testing Internal Methods

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:

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

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

Project File Change

Assuming we have a project called Animals and a unit test project called Animals.Tests. The Animals project file which contains the internal method can be modified in visual studio with the following:

  <ItemGroup>
    <AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">
      <_Parameter1>$(MsBuildProjectName).Test</_Parameter1>
    </AssemblyAttribute>
  </ItemGroup>

Source File change

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

using System.Runtime.CompilerServices;

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

namespace Animals
{
    public class Dog
    {
        internal string Chase(string animal)
        {
            return $"Dog chases {animal}";
        }
    }
}

Conclusion

Out of the two methods above, I much prefer the project file approach, since this is the most flexible. I don’t like the source file approach, since this would mean sprinkling the attribute over the source code.