Funny issue with Code Coverage and Reflection

2012-01-09

Just stumbled upon a tricky change which happens to your assemblies when you're running your tests with Code Coverage enabled.

Take the following piece of code:
var types = typeof(Program).Assembly.GetExportedTypes();
foreach (Type t in types)
{
     // ...
}

In our case the behavior of the code under test changed completely between a debug run, a normal test run and a run with Code Coverage enabled. And the most difficult issue is that you can't gather Code Coverage data with the debugger attached.

Answer after the break.
The issue seems to be caused by Publicize. This little tool only runs when Code Coverage is enabled and will make sure that for all private types a public version becomes available. We were loading assemblies at runtime using Assembly.Load and and as such GetExportedTypes would not only return the public types, but it will also return all wrapped non-public types.

In our case it even caused our test to fail with a FileNotFoundException. This was caused by the fact that one of the private types depended on an Assembly which wasn't referenced by the test project. As this type was never loaded under normal circumstances, the code would work just fine, but now that all private types were being returned, the type could not be loaded because the referenced Assembly could not be found.

I'm wondering which other methods might behave differently after running Publicize...
 

Most Reading