Click here to Skip to main content
15,885,216 members
Articles / Programming Languages / C#
Tip/Trick

Code Coverage And Generics

Rate me:
Please Sign up or sign in to vote.
5.00/5 (7 votes)
2 Apr 2011CPOL 16K   1   5
How to get that last little nagging line to be covered...
I was recently trying to achieve a perfect 100% code coverage (don't ask) for a particular class I was working on, when I ran across an annoying problem.

A generic constructor...

The following code would only give me partial coverage when executed:

public class GenericMethod<T> where T : new()
{
  ...
  T item = new T();
  ...
}


In and of itself, not a very daunting looking line. But alas, it was a worthy foe. For without proper documentation and explanation, Visual Studio indicated that I was only partially covering this simple line.

After much Googling, I still didn't come up with any answers. So, after some head scratching, I finally tried a struct, because up until then, all of my unit tests were using classes.

Voilà!

Visual Studio complained no more and neither did I.

So, if you're ever in dire need of 100% code coverage and run across a partially covered line in a generic method, try using both classes and structs.

Granted, I could have restricted the type more, but I needed to support both. :)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
United States United States
Since I've begun my profession as a software developer, I've learned one important fact - change is inevitable. Requirements change, code changes, and life changes.

So..If you're not moving forward, you're moving backwards.

Comments and Discussions

 
QuestionThanks Pin
RobRimmer2k821-Oct-12 23:53
RobRimmer2k821-Oct-12 23:53 
AnswerRe: Thanks Pin
Andrew Rissing22-Oct-12 4:08
Andrew Rissing22-Oct-12 4:08 
GeneralWhat do you mean by coverage? Pin
jeramyRR5-Dec-11 21:55
jeramyRR5-Dec-11 21:55 
GeneralRe: Code coverage. As in, the percentage of the code covered (o... Pin
Andrew Rissing6-Dec-11 3:55
Andrew Rissing6-Dec-11 3:55 
GeneralReason for my vote of 5 Very valuable information. Thanks fo... Pin
Manfred Rudolf Bihy1-Apr-11 3:59
professionalManfred Rudolf Bihy1-Apr-11 3:59 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.