Unit Test: Internal Type versus public

In this post, I’d like to explain how to use the internal type instead of public during the test phase.

I don’t spent a lot of words, so I share you the inital point. In your solution, you have two projects:

  • MyIdea
  • MyIdea.Test

Is it simple? YES!

Internal vs Public

In “MyIdea” you have the full logic on your project. In the following lines, you can see a fake class

1
2
3
4
internal class MyIdeaFakeClass
{
    public bool DoNothing() { return true; }
}

MyIdeaFakeClass is a specific class for this project, for this reason I don’t want to use public.

Unit Test

In this way I have a problem in my unit test project. I cannot use the following code:

1
2
3
4
5
6
7
[Fact]
public void DoNothingTest()
{
    MyIdeaFakeClass item = new MyIdeaFakeClass();
    var result = item.DoNothing();
    Assert.Equal(true, result);
}

The reason is very simple:

SeverityCodeDescription
ErrorCS0122‘MyIdeaFakeClass’ is inaccessible due to its protection level

Ops …

❌ ‘MyIdeaFakeClass’ is inaccessible due to its protection level

How can I solve this?

Solution

If you want to solve this exception you have two ways:

  • change internal to public (bad idea)
  • edit the project

In this post, I teach you how to change the file project (csproj)

1
2
3
4
5
<ItemGroup>
  <AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">
    <_Parameter1>MyIdea.Test</_Parameter1>
  </AssemblyAttribute>
</ItemGroup>

Now, you can only save the csproj and the error CS0122 doesn’t block your work.

♻️ Did you know this tip? Share it with your friends!