Excluding Code from Code Coverage Metrics

I was working on a small application today and it included a very thin wrapper around .NET Framework classes to make my code easier to test (i.e. providing interfaces and adapters for .NET Framework classes so I can mock them out). Because these wrappers are very hard to test (because of the APIs that they wrap) and because testing them really would be testing .NET Framework code and not the code I was writing I wanted to exclude these wrappers from code coverage metrics.

This wasn’t possible in VSTS 2008 / .NET 3.5 so I thought I’d find out if it was now possible in VSTS 2010 / .NET 4.0 and one of my colleagues informed me that it is. A new attribute is available in System.Diagnostics.CodeAnalysis called ExcludeFromCodeAnalysis. One caveat to using this attribute is that the assembly being tested must target .NET Framework 4.0 for the attribute to be available (because it is in a .NET Framework 4.0 assembly). It will also only be honored by the testing functionality in VSTS 2010.

Here’s an example of it in use:

using System.Diagnostics.CodeAnalysis;

using System.IO;

namespace Services

{

    [ExcludeFromCodeCoverage]

    class Win32FileSystem : IFileSystem

    {

        void IFileSystem.Delete(string path)

        {

            File.Delete(path);

        }

        string IFileSystem.GetTempFileName()

        {

            return Path.GetTempFileName();

        }

    }

}