65.9K
CodeProject is changing. Read more.
Home

Code Coverage And Generics

starIconstarIconstarIconstarIconstarIcon

5.00/5 (7 votes)

Mar 31, 2011

CPOL
viewsIcon

17006

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