Search code examples
c#testinginterfacemockinginternals

Implement Internal Interface in Tests


I have made internal classes and functions visible to my test project via:

<ItemGroup>
  <AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleToAttribute">
    <_Parameter1>MyProject.Tests</_Parameter1>
  </AssemblyAttribute>
</ItemGroup>

This works fine, but now I am trying to implement the following internal interface in my tests for mocking purposes:

internal interface IRepository
{
    void Function1();        
}    

In my test code, I have implemented the above interface as follows:

internal class MockRepository : IRepository
{
    internal void Function1()
    {
        // Do something.
    }        
}

However, I am getting the following error:

'MockRepository' does not implement interface member 'IRepository.Function1()'. 'MockRepository.Function1()' cannot implement an interface member because it is not public. [MyProject.Tests]

It seems that InternalsVisibleToAttribute only applies to classes and functions.

Do I really have to make my internal interface public to let tests mock it, or is there a way to keep it internal?

I ask because I want to keep as many things accessible only to my project and its tests.


Solution

  • I just figured it out. Turns out all I needed to do was make the implementation itself public.

    The mock class itself can stay internal:

    internal class MockRepository : IRepository
    {
        public void Function1()
        {
            // Do something.
        }        
    }