Thursday, June 30, 2011

Easily exclude generated proxies from your code coverage

This is just a quick heads-up that many of you might already know about: partial classes easily enable you to add an attribute to an existing class by just adding an empty partial class definition for the same class in another source code location that just has that attribute on it.

Adding an attribute like this can be used to exclude the generated code of a webservice proxy from unit test code coverage by adding a DebuggerNonUserCode attribute to the relevant classes, like so:

// Add DebuggerNonUserCode attribute to generated
// proxy classes to exclude it from code coverage.

namespace Your.ServiceProxy.Namespace
{
 using System.Diagnostics;
 [DebuggerNonUserCode] public partial class YourWebService { }
 [DebuggerNonUserCode] public partial class SomeServiceDto { }
 [DebuggerNonUserCode] public partial class AnotherServiceDto { }
 // et cetera
}

As long as the service keeps using the same classnames, this solution even enables you to regenerate your proxy without losing the code coverage exclusion of the proxy (if you put this code in place not touched on regeneration).

Nifty, huh? ;-)