Wednesday, November 10, 2010

Creating mock DataTable and DataRow objects

For the purpose of testing….
DataRow cannot be instantiated directly as its constructor is protected.
First create the DataTable with the columns you want it to have and then call DataTable.NewRow(). (This just returns a new DataRow object with the schema as specified in DataTable, to add it to the DataTable call DataTable.Rows.Add().

    DataTable table = new DataTable();
    table.Columns.Add("Column1", typeof(int));
    table.Columns.Add("Column2", typeof(string));
    table.Columns.Add("Column3", typeof(string));
    table.Columns.Add("Column4", typeof(DateTime));
    DataRow dataRow = table.NewRow();
    dataRow["Column1"] = 1;
    dataRow["Column2"] = "1";
    dataRow["Column3"] = "1";
    dataRow["Column4"] = DateTime.Now;

1 comment:

Bob said...

This is useful for creating test data for the purpose of unit testing. However, it isn't really demoing mock objects as it is using concrete DataTable and DataRow objects. To be clear, here is a practioners description of a mock object from the IBM Developers website...

"Mock objects are a useful way to write unit tests for objects that act as mediators. Instead of calling the real domain objects, the tested object calls a mock domain object that merely asserts that the correct methods were called, with the expected parameters, in the correct order."

That's not to say the example given isn't useful in creating unit tests, only that it doesn't demonstrate Mock DataTable or DataRow objects.