Click here to Skip to main content
Click here to Skip to main content
Go to top

Code Coverage And Generics

, 2 Apr 2011
Rate this:
Please Sign up or sign in to vote.
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. Smile | :)

License

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

Share

About the Author

Andrew Rissing
Software Developer (Senior)
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 PinmemberRobRimmer2k821-Oct-12 23:53 
AnswerRe: Thanks PinmemberAndrew Rissing22-Oct-12 4:08 
GeneralWhat do you mean by coverage? PinmemberjeramyRR5-Dec-11 21:55 
GeneralRe: Code coverage. As in, the percentage of the code covered (o... PinmemberAndrew Rissing6-Dec-11 3:55 
GeneralReason for my vote of 5 Very valuable information. Thanks fo... PinmvpManfred R. Bihy1-Apr-11 3:59 

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

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

| Advertise | Privacy | Mobile
Web01 | 2.8.140926.1 | Last Updated 2 Apr 2011
Article Copyright 2011 by Andrew Rissing
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid