Use attribute to omit code from coverage analysis in Visual Studio

我是研究僧i 提交于 2019-11-30 06:46:59
Shrike

Starting with VS2010 we have ExcludeFromCodeCoverageAttribute. Commenters have noted this to work in NCover as well as DotCover + NUnit. Example usage:

[ExcludeFromCodeCoverage]
public class myUntestableClass
{ }

Also see this link. They suggest using VSInstr as command line tool, it have /EXCLUDE options (it's not as handy).

I've found some information on a couple of Diagnostics attributes DebuggerNonUserCodeAttribute and DebuggerHiddenAttribute that indicates that using these attributes will cause the coverage analyzer in VS to leave these out of its results. I've tried it with the DebuggerNonUserCodeAttribute and it seems to work. I can probably live with this for most of the classes that I'm thinking of, though I don't like the side effect of not being able to step into these classes. That shouldn't be a problem for the wrapper classes, but it may end up being so with classes that are inherently hard to test and I need debugger access to.

I'm still looking for alternatives, though.

With NCover you can create an attribute and then tell NCover to ignore that attribute.

In our projects, we have defined this attribute (no namespace, so it is easy to use):

public class CoverageExcludeAttribute : Attribute { }

We use NAnt, so we have a target that looks like this:

<target name="unittests" description="run nunit tests" >        
    <ncover
        ....
        excludeAttributes="CoverageExcludeAttribute"
    />
</target>

Question 9 in the NCover FAQ describes this method. We based our solution on this.

Alternatively, you can use the exclude feature of the NCoverExplorer to exclude namespaces and assemblies from the final report. This merely removes the data from the report, but the end result is the same.

We use both techniques.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!