Search code examples
c#typesmstest

reverse typeof(T) to use type in tests


I have a factory method Create<T>() which returns an instance of a given interface type T. The Factory pattern works, but now I have to write test in MSTest for our Factory. The tests should check if the instance of our create method is the right one. Basically, I want to do something like this:

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

The problem is, that the DataRow can only have a typeof(T) and not T as a parameter. So I have to revert the typeof(T) operator.

How can I achieve this? Is there a better way to do something like this?

[EDIT]

[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 failed, because they are not the same. Look closely:

Message: Assert.AreEqual failed.

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

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


Solution

  • You need to use reflection to achieve this :

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