反转 typeof(T) 以在测试中使用类型

reverse typeof(T) to use type in tests

我有一个工厂方法 Create<T>(),它 returns 给定接口类型 T 的一个实例。工厂模式有效,但现在我必须在 MSTest 中为我们的工厂编写测试。测试应该检查我们创建方法的实例是否正确。基本上,我想做这样的事情:

[DataTestMethod]
[DataRow(typeof(Member), typeof(MemberImpl))]
public void Test1(Type interfaceType, Type implType)
{
    implType instance = PlanungContribution.Create<interfaceType>();
}

问题是,DataRow 只能有一个 typeof(T) 而不是 T 作为参数。所以我必须还原 typeof(T) 运算符。

我怎样才能做到这一点? 有没有更好的方法来做这样的事情?

[编辑]

[DataTestMethod]
[DataRow(typeof(Mitarbeiter), typeof(MitarbeiterImpl))]
public void Test1(Type interfaceType, Type baseType)
{
    var t = typeof(ModelContributionPlanungEF6).GetMethod("Create").MakeGenericMethod(interfaceType).Invoke(PlanungContribution, new object[0]);
    Assert.AreEqual(baseType, t);
}

Assert.AreEqual失败,因为它们不一样。仔细看:

Message: Assert.AreEqual failed.

Expected: DP.PMS.EF6.Planung.MitarbeiterImpl (System.RuntimeType).

Actual:DP.PMS.EF6.Planung.MitarbeiterImpl (DP.PMS.EF6.Planung.MitarbeiterImpl).

你必须先通过反射调用泛型方法并调用它。然后检查返回的类型:

[DataTestMethod]
[DataRow(typeof(Member), typeof(MemberImpl))]
public void Test1(Type interfaceType, Type implType)
{
    var method = typeof(PlanungContribution).GetMethod("Create").MakeGenericMethod(interfaceType);
    var instance = method.Invoke(null, new object[0]);
    var type = instance.GetType();
    Assert.AreEqual(type, implType);
}

您需要使用反射来实现:

typeof(PlanungContribution).GetMethod("Create").MakeGenericMethod(interfaceType)
    .Invoke(null /*Instance to call on , if static pass null */, new object[0]);