Quantcast
Channel: Programming Tidbits - Unit Testing
Viewing all articles
Browse latest Browse all 2

Using The [InternalsVisibleTo] Attribute To Allow Unit Testing of Internal Classes

$
0
0

Unit testing purists will argue that you don't need to test your internal classes, that all of your code should be tested through its public API. Generally, I agree, but like everything else, it's not always black or white. In some situations, I think it's necessary.

Regarding unit tests, I go by the practice of creating a separate tests project for each tested project (named {TestedProjectName}.Tests), which, in the above scenario, prevents me from testing the internal classes of the tested project.

One of the alternatives is to write the tests in the same assembly of the tested code. This is a bad idea for the following reasons:

  • The tested module becomes dependent on the unit testing framework.
  • The unit tests will be shipped with the rest of the code, which is not always desirable. And if you think to solve it by recompiling the code without the tests, it just means that the final product is not really tested.
  • There is no real separation between production code and testing code.
Another option is to use reflection in order to create the internal classes, but it will only complicate the tests.
 
The simplest and most elegant solution is to decorate the tested project's assembly with the [InternalsVisibleTo] attribute. For example, adding the following code to MyProject's AssemblyInfo.cs will give MyProject.Tests access to all of MyProject's internal members.
[assembly : InternalsVisibleTo ("MyProject.Tests")]

By using the [InternalsVisibleTo] attribute, we can keep following the practice of a separate tests project for each tested project, and still be able to test internal classes when we really need to.


Viewing all articles
Browse latest Browse all 2

Trending Articles