25

Background: Visual Studio 2008, C#, .Net 3.5.

I have a number of utility classes that are simply not unit-testable. This is mainly because they interact with resources (e.g. databases, files etc).

Is there a way I can decorate these classes so that the Visual Studio Code Coverage engine will ignore them, so not decreasing the code coverage percentage?

Chris Arnold
  • 5,753
  • 5
  • 35
  • 55
  • Dupe: http://stackoverflow.com/questions/1289429/use-attribute-to-omit-code-from-coverage-analysis-in-visual-studio – tvanfosson Oct 21 '09 at 19:05

4 Answers4

31

When you upgrade your project to .NET 4, you'll get the ExcludeFromCodeCoverageAttribute Class.

brickner
  • 6,595
  • 3
  • 41
  • 54
21

There is an answer in this article about how to use [System.Diagnostics.DebuggerHidden] or [System.Diagnostics.DebuggerNonUserCode] Attributes to exclude methods from code coverage.

Update as per David's comment:

As of .NET 4.0 there is a dedicated attribute for this: [ExcludeFromCodeCoverage]

John K
  • 28,441
  • 31
  • 139
  • 229
  • 2
    A point of caution (from the above article) - "DebuggerHidden will prevent you from stepping into the method or setting breakpoints in that code and DebuggerNonUserCode will hide the code as (sic) debug time and automatically step over it." – Dunc Mar 18 '10 at 10:19
  • 5
    Important note: As of .NET 4.0 there is a dedicated attribute for this: `[ExcludeFromCodeCoverage]` – David Apr 01 '14 at 12:14
  • Thanks @David your note has been added to the answer. – John K Apr 26 '14 at 18:14
0

One of the reason you want to write unit-tests is to make your code loosely coupled. You can read this article if you're interested in learning how to write loosely coupled code (in case you don't know how).

Saying that you can try to use tools like TypeMock that can help you mock your objects even if you don't write them using Dependency Injection principle.

TypeMock was the first Mock Framework I used. I switch to Rhino Mocks because with TypeMock I didn't have to be discipline enough to write loosely coupled code.

Vadim
  • 21,044
  • 18
  • 65
  • 101
  • 3
    We write very good, loosely coupled code; but at some point, something has to actually access a resource! – Chris Arnold Oct 21 '09 at 19:58
  • You create wrappers for these resources and use wrappers in your production code instead of resources itself. Check the link in my answer. – Vadim Oct 21 '09 at 20:28
0

I imagine there is more than one class in your test project and so an option to consider would be to directly exclude the test project from coverage. You can achieve that by adding this code in your ClassTests.csproj :

<ItemGroup>
        <AssemblyAttribute Include="System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute" />
</ItemGroup>
Francois Borgies
  • 2,378
  • 31
  • 38