Overview Of InternalsVisibleToAttribute Class In .NET

Using the modifier ‘public’ on any member-level fields or methods can be a risky move in any environment with complicated systems running. At the same time, you may want to test these fields and methods with an external project. Ideally, dependency inject can be used to test the public surface of your applications and expose any errors. However, in rare cases, dependency injection can become unwieldy or simply unfeasible.
 
The assembly attribute InternalsVisibleTo can be utilized in this scenario to unit test individual methods from an external project without exposing said methods on the application’s public surface. I would like to share with you a mock-up of what this would look like.
 
We will have three projects within our solution: MainProject, TestProject, and UnrelatedProject. MainProject is where the InternalsVisibleTo assembly attribute will be implemented. TestProject will demonstrate the use of MainProject’s internal method from an external source (as a ‘friend’ assembly). UnrelatedProject will represent an existing application in our environment that should not (and will not) be allowed to use MainProject’s internal members.
 
As you can see in the source code, when [assembly:InternalsVisibleTo(“TestProject”)] is implemented, we see the following:
 
ClasswithAccess
 
ClassToExpose
 
test project
 
Code
 
See by the red underlines which method calls will not compile.
 
This is exactly the result we would expect: the method with an internal access-level modifier is now visible to TestProject, but not UnrelatedProject. Neither can reach the private method, and both can reach the public method.
 
Further information on MSDN can be found here.


Recommended Free Ebook
Similar Articles