Excluding Code from MSTest Coverage Results

In order to write testable code, I sometimes need to add internal test APIs which take ASP.NET abstractions such as HttpContextBase.  At runtime I use the public wrapper, however my tests just call directly into the internal helper:

public void DoSomething() {
    DoSomethingInternal(new HttpContextWrapper(HttpContext.Current);

internal void DoSomethingInternal(HttpContextBase context) {
    // do actual work

However, I’ve now skewed my code coverage numbers because my tests will never execute the public wrapper.  Prior to .NET 4, you could exclude the untestable code from coverage by attributing it with the DebuggerNonUserCodeAttribute or the DebuggerHiddenAttribute.  Unfortunately this ends up altering the debugger behavior as well.

In .NET 4, you should use the new ExcludeFromCodeCoverageAttribute.  Unfortunately, this attribute wasn’t attributed with Conditional(“CODE_COVERAGE”), so it’s up to you to exclude it from your non-coverage builds:

public void DoSomething() { ... }

Alternatively, you could strip the attributes in a post-build step to avoid writing the excess directives…

Comments (0)