![](/img/trans.png)
[英]Pass an instance of a generic type as a parameter on a dynamic instance of a generic class
[英]Creation of a new instance of generic type parameter not getting code coverage
我通過代碼覆蓋運行我的代碼,下面的行顯示1塊未覆蓋。
誰能告訴我該行的哪一部分沒有執行?
一個例子:
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
{
}
和測試方法
[TestMethod]
public void TestMethod1()
{
Class1 ex = new Class1();
ex.CreateEntity<TEx>();
}
更改約束以強制TExample
成為類:
public abstract IExample CreateEntity<TExample>() where TExample : class, IExample, new();
如果您通過ILSpy之類的工具運行已編譯的代碼,您將看到未獲得覆蓋的塊:
TExample temp = (default(TExample) == null) ? Activator.CreateInstance<TExample>() : default(TExample);
return temp;
它正在執行檢查以查看傳遞給泛型的類型是引用類型還是值類型。 通過強制它成為一個類,將刪除此檢查。 在此處閱讀有關默認關鍵字的更多信息: http : //msdn.microsoft.com/en-us/library/xwth0h0d.aspx
獲得完整代碼覆蓋率的另一種方法是使用實現IExample
的結構:
public struct S1 : IExample
{
}
然后添加此測試:
[TestMethod]
public void StructTest()
{
Class1 ex = new Class1();
ex.CreateEntity<S1>();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.