May 3, 2010

Exclude from Code Coverage (Visual Studio 2010)

 

I was working on a library that adds some customer specific functionality to web services and WCF. I decided to have it very highly covered by unit tests. Unfortunately there is some static functionality in WCF (OperationContext) that is hard to be used in unit tests (it throws). So I wrapped this code behind a custom C# interface with a production implementation calling OperationContext and an (independant and fast) unit test implementation/mock. The small and simple production implementation had some negative impact on Visual Studio (instruction) code coverage (being below 100%). I figured out how to exclude this piece of code.

The way to do this is to add the [ExcludeFromCodeCoverage] attribute to class, property, method or event:

namespace MyTrials

{

    // [ExcludeFromCodeCoverage]

    public class NotCoveredClass

    {

        [ExcludeFromCodeCoverage]

        public string NotCoveredProperty { get; set; }

        public string CoveredProperty { get; set; }

 

        [ExcludeFromCodeCoverage]

        public EventHandler<EventArgs> OnNotCoveredEvent { get; set; }

        public EventHandler<EventArgs> OnCoveredEvent { get; set; }

 

        [ExcludeFromCodeCoverage]

        public void NotCoveredMethod()

        {

        }

 

        public void CoveredMethod()

        {

        }

    }

 

    public class CoveredClass

    {

    }

}

Write some more useful unit tests than I did for this post:

[TestMethod]

public void CodeCoverage_ExcludeWith_ExcludeFromCodeCoverage_FromClassMethodPropertyEvent()

{

    CoveredClass target = new CoveredClass();

    NotCoveredClass target2 = new NotCoveredClass();

 

    target2.CoveredMethod();

}

 

to have it excluded:

image

Other ways I’ve seem were to add [System.Diagnostics.DebuggerHidden] or [System.Diagnostics.DebuggerNonUserCode] to methods – but with some side effects!

No comments:

Post a Comment