Search code examples
c#unit-testinggeneric-type-argument

Unit Testing of Method With Generic Type Argument


I have a system in which all my classes extend the base class Sol.Data.Object. In this base class I have one method for retrieving data from database:

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));
       .....
}

I will call this method for example like this: Sol.Movie.ReadId("dbo", 2)

I used Visual Studio 2010 to create a unit test for this method:

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>();
}

How should I define expected type? I tried typeof(ObjectType) but it gives me compile error.

Thanks for helping!


Solution

  • I used this method to fix the problem:

    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>();
    }
    

    Don't know whether this is the best way to do this though.