0

I don't know why i'm having this behavior with my code coverage, maybe someone knows the reasson. As you may know, code coverage is blue when reached, red when not reached, yellow when partially reached a line of code.

I coded a little mapper that receives a IDataReader and turns into object thanks to reflection.

internal IEnumerable<T> Convert<T>(System.Data.IDataReader dataReader) where T : new()
{
    var columns = this.GetColumns(dataReader); // get a list of column name... not important.
    var result = new List<T>();

    while (dataReader.Read())
    {
        var nuevoObjeto = new T();  // <-- this line is yellow in code coverage.

        foreach (var item in columns)
        {
            var pi = nuevoObjeto.GetType().GetProperty(item);

            pi.SetValue(nuevoObjeto, dataReader[columns.IndexOf(item)]);
        }

        result.Add(nuevoObjeto);
    }

    return result;
}

As you can see, the yellow line is not a conditional like IF or WHILE... is just a simple "new T" And if you debug this code, debug reaches very well that line, in fact test is green with expected results.

Test performs this steps.

  1. Fake IDataReader (with nSubstitute)
  2. Only 1 result on the datareader.
  3. T is tested with only one TestClass... like USERTEST.

hope someone knows why this happens... thanks!

Yogurtu
  • 2,656
  • 3
  • 23
  • 23
  • Look at the IL that is generated. Odds are there is some statement (maybe a generated catch) that is not getting hit by the code coverage. – John Koerner Jan 09 '15 at 00:15
  • possible duplicate of [Creation of a new instance of generic type parameter not getting code coverage](http://stackoverflow.com/questions/18257285/creation-of-a-new-instance-of-generic-type-parameter-not-getting-code-coverage) – John Koerner Jan 09 '15 at 00:21

2 Answers2

2

The IL that gets generated for that line is equivalent to:

T nuevoObjeto = (default(T) == null) ? Activator.CreateInstance<T>() : default(T);

This allows structs to be used for the generic type as they satisfy the new constraint.

So, if you want 100% code coverage, test your generic method with a struct or change the constraint to require that the generic type be a class using where T : class

John Koerner
  • 37,428
  • 8
  • 84
  • 134
  • So, there is the IF that makes yellow that sentence. Indeed I just changed my code with class on the constraint and it reached 100% coverage. Thanks. – Yogurtu Jan 09 '15 at 20:38
0

Try to test it also with struct or add class constraint to the generic method - http://www.codeproject.com/Tips/175592/Code-Coverage-And-Generics

Lukas.Navratil
  • 590
  • 4
  • 12
  • Do you mean sample of class constraint? `Convert(System.Data.IDataReader dataReader) where T : class, new()`. If you meant test with struct, I don't know which testing framework is author using (he didn't provide code of the test), so I can't write the code... – Lukas.Navratil Jan 09 '15 at 00:48