问题
I have some classes that, for one reason or another, cannot be or need not be unit tested. I'd like to exclude these classes from my coverage metrics so that I can get a better feel for the coverage on the classes I actually care about. Right now I have to exclude the results after the fact. What I would like to do is use an attribute to mark those classes as excluded so that they aren't included to begin with. Is there any way to decorate a class with an attribute that will automatically exclude it from coverage analysis? Either VS coverage analysis or nCover will work.
FWIW, these are classes that I can assure myself by inspection that the code is correct. Mostly they are wrapper classes around existing framework classes that I've introduced in order to be able to mock the framework class out. Since the wrapper's get mocked out they don't get tested. That's ok because all they do is wrap the framework class' methods that I care about.
回答1:
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).
回答2:
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.
回答3:
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.
来源:https://stackoverflow.com/questions/1289429/use-attribute-to-omit-code-from-coverage-analysis-in-visual-studio