Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use attribute to omit code from coverage analysis in Visual Studio

Tags:

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.

like image 997
tvanfosson Avatar asked Aug 17 '09 17:08

tvanfosson


2 Answers

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).

like image 81
Shrike Avatar answered Sep 24 '22 01:09

Shrike


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.

like image 36
tvanfosson Avatar answered Sep 21 '22 01:09

tvanfosson