Where should you put your unit tests? In the same assembly or in an assembly of its own?
Phil Haack organized a poll on the subject which at the time of this writing shows that nine out of ten developers would go for separate projects. One out of ten would put them in the same assembly, and a small fraction would simply do “other”. Are there, by the way, any more options available?
But when the tests are in a different assembly than the code being tested – wouldn’t the classes and methods under test need to be public? Declaring them as public just for the sake of testing would definitely break the encapsulation. Until quite recently, I belonged to the 10% that put their tests along with the code to be tested, for this particular reason. This solved the encapsulation problem, but came at the price of having to ship the full tests to the customer. It also made it hard for me to put the test data – in this case, images – as resources in the assembly, because that would further have increased the binary footprint of the application.
Somehow I managed to miss the introduction of the InternalsVisibleTo attribute that has been around since .NET 2.0. You add it the assemblies containing the code under test and let it point at your test assemblies, which can then access any internals they need.
When working with signed assemblies, you will need to declare both the name and the public key of the assembly being referenced. It’s not unlikely that you run into some hassle getting the public key string of the unit test assembly. Luckily, Tyler Holmes gives simple description on how this can be done.
I’m sure there still are situations when you’d still want to keep tests and code being tested together. However, access to internal classes and methods shouldn’t be the main reason.