Reputation: 93
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).
Upvotes: 0
Views: 1167
Reputation: 37070
You have to invoke the generic method via reflection first and invoke it. Afterwards check the returned type:
[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);
}
Upvotes: 0
Reputation: 250136
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]);
Upvotes: 1