Unit testing for a project that some classes inside it is marked with internal keyword

Have you ever written a component that used for a other solution? This is meaning you write a component (for example, a third party, a extensions,...). So we usually use the "internal" keyword inside all classes in your component. Is it right?  And as you know if you use the "internal" keyword, you will not access from outside. Now I assume that you have a testing project out side the component project. How can you access to the internal classes inside your component project? If you try access to this component project, you will get one error "Cannot access internal class <ClassName> here"
This post only a tips and tricks, so you can use it to access to the component that mark with the "internal" keyword. It is just simple is you must tell to the component project to assign enough permission to a assembly that want to access to your component.
In order to make this, you are only need open the AssemblyInfo.cs file, and append one line to the end of this file. And this line is:
[assembly: InternalsVisibleTo("<Namespace of the assembly that you want to access to this assembly>")]
For example, I have the component project with namespace is Cik.Domain and the Unit Testing project is Cik.Domain.Testing. So I must open the AssemblyInfo.cs file inside the Cik.Domain project and add one line at the end of this file as: [assembly: InternalsVisibleToCik.Domain.Testing")]
Now compile all projects, and all things will work well. You shall have enough visible to use some classes inside your component and do unit testing for it. I hope this tips and tricks will be useful for you.

3 Comments

  • Just a quick addition to this post:

    If the project the component you are testing is within a signed assembly then you also need to add the public key to your test project. The line you add to the component's assembly would then be

    [assembly: InternalsVisibleTo(", PUBLIC_KEY_TOKEN")]

    After that all should compile fine.

  • Your reply is very good to me. Thanks for your comment, man!

  • Hi again!

    It's good to know about such feature. In the past I always marked such classes as public but that's a bad custom.

    Best wishes!

Comments have been disabled for this content.