How to test internals in C# if you don’t have access outside the assembly? 🤔

Jorge Freitas
2 min readSep 5, 2021
Photo by bruce mars on Unsplash

It is really important to have code with test coverage, but it is also important to respect access modifiers and do not make everything public just to have access in your unit tests.

But how can you test a class if it is declared as internal? Should you avoid an internal access modifier just o be able to test it? Because we usually have our tests in another project and then we don’t have access to it.

Problem

You cannot access the internal classes outside the assembly.

Visual studio showing an error when we try to access to internal class

Solution

Basically, add the following ItemGroup to your project (the project where you have your class internal) and then we can access internals in your UnitTests project.

Include InternalsVisibleTo in cssproj
Internal classes can be accessed using unit tests

And voila! That’s it 🙌

As usual, you can access the code in my repository

Conclusion

The unit test is simple but here I just wanted to show you that it is possible and how we can do it. Well, as a conclusion we should not avoid some access modifiers just to be able to test them.

References

--

--