Reputation: 9975
I've run my code through code coverage and the line below shows 1 block as not covered.
Can anyone tell me which part of that line isn't executing?
An Example to play with:
public abstract class Base
{
public abstract IExample CreateEntity<TExample>() where TExample : IExample, new();
}
public class Class1 : Base
{
public override IExample CreateEntity<TExample>()
{
IExample temp = new TExample();
return temp;
}
}
public interface IExample
{
}
public class TEx : IExample
{
}
and the test method
[TestMethod]
public void TestMethod1()
{
Class1 ex = new Class1();
ex.CreateEntity<TEx>();
}
Upvotes: 8
Views: 323
Reputation: 38077
Change your constraint to force the TExample
to be a class:
public abstract IExample CreateEntity<TExample>() where TExample : class, IExample, new();
If you run your compiled code through a tool like ILSpy, you will see the block that is not getting coverage:
TExample temp = (default(TExample) == null) ? Activator.CreateInstance<TExample>() : default(TExample);
return temp;
It is performing a check to see if the type passed to the generic was a reference type or a value type. By forcing it to be a class, this check will be removed. Read more on the default keyword here: http://msdn.microsoft.com/en-us/library/xwth0h0d.aspx
Another way to get complete code coverage would be to use a struct that implements IExample
:
public struct S1 : IExample
{
}
And then add this test:
[TestMethod]
public void StructTest()
{
Class1 ex = new Class1();
ex.CreateEntity<S1>();
}
Upvotes: 6