泛型类型参数的新实例的创建没有得到代码覆盖率 [英] Creation of a new instance of generic type parameter not getting code coverage
问题描述
我碰到我通过代码覆盖和代码下图为该行1块不是盖的。
谁能告诉我这是行的一部分不执行?
这是例子玩:
公共抽象类基地
{
公共抽象的IExample CreateEntity< TExample>()其中TExample:的IExample,新();
}
公共类的Class1:基本
{
公众覆盖的IExample CreateEntity< TExample>()
{
的IExample TEMP =新TExample ();
返回温度;
}
}
公共接口的IExample
{
}
公共类TEX:的IExample
{
}
和测试方法
[TestMethod的]
公共无效TestMethod1()
{
1级EX =新1级();
ex.CreateEntity<&TEX GT;();
}
更改您的约束,强制 TExample
是一个类:
公共抽象的IExample CreateEntity< TExample> ()其中TExample:类的IExample,新();
如果您通过像ILSpy工具中运行已编译的代码,你会看到,是没有得到该块覆盖范围:
TExample TEMP =(默认值(TExample)== NULL)? Activator.CreateInstance< TExample>():默认(TExample);
返回温度;
据执行检查,看是否传递到通用的类型是引用类型或值类型。通过迫使它是一个类,这个检查将被删除。了解更多关于默认的关键字: http://msdn.microsoft.com/en-us/library/ xwth0h0d.aspx
另一种方式来获得完整的代码覆盖率将使用结构实现的IExample
:的IExample
{
}
$ C $:
C>
然后添加这个测试:
[TestMethod的]
公共无效StructTest()
{
1级EX =新1级();
ex.CreateEntity< S1>();
}
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>();
}
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>();
}
这篇关于泛型类型参数的新实例的创建没有得到代码覆盖率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!