具有泛型类型参数的方法的单元测试

时间:2013-01-05 09:57:05

标签: c# unit-testing generic-type-argument

我有一个系统,其中所有类都扩展了基类Sol.Data.Object。在这个基类中,我有一种从数据库中检索数据的方法:

public static ObjectType ReadById<ObjectType>(string schema, long id)
{
    SqlCommand command = User.CreateCommand(string.Format("{1}.Retrieve{0}",
                                            typeof(ObjectType).Name,
                                            schema),
                                            new SqlParameter("@ID", id));
       .....
}

我将调用此方法,例如:      Sol.Movie.ReadId("dbo", 2)

我使用Visual Studio 2010为此方法创建单元测试:

public void ReadByIdTestHelper<ObjectType>()
{
    string schema = "dbo";
    long id = 1;
    ObjectType expected = default(ObjectType); //What should I put in here?!
    ObjectType actual;
    actual = Sol.Data.Object.ReadById<ObjectType>(schema, id);
    Assert.AreEqual(expected, actual);
    Assert.Inconclusive("Verify the correctness of this test method.");
}

[TestMethod()]
public void ReadByIdTest()
{
    ReadByIdTestHelper<Sol.Movie>();
}

我应该如何定义预期类型?我试过typeof(ObjectType),但它给了我编译错误。

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

我使用此方法来解决问题:

public void ReadByIdTestHelper<ObjectType>()
{
    string schema = "dbo";
    long id = 1;
    Sol.Movie movie = new Movie();
    ObjectType actual;
    actual = Sol.Data.Object.ReadById<ObjectType>(schema, id);
    Assert.AreEqual((actual is ObjectType), true);
}

[TestMethod()]
public void ReadByIdTest()
{
    ReadByIdTestHelper<Sol.Movie>();
}

不知道这是否是最好的方法。