Today I had to work with some legacy code. It was originally written in Delphi and then converted line by line to C#. Before changing anything in the code I decided to create unit tests and make sure that I have 100% coverage.
One of the thing I had to do in my unit test is to mock DataTable. Here are the steps I made during mocking.
- Create needed columns in a DataTable.
- Create a new DataRow.
- Assign values to the row.
- Finally add the row to the DataTable.
Repeat steps 2- 4 for each row you want to add to your DataTable.
Here’s the example:
1: [Test]
2: public void HolidayTest()
3: {
4: MockRepository mocks = new MockRepository();
5: ICompanyDAL dalMock = mocks.CreateMock<ICompanyDAL>();
6: // Create DataTable
7: DataTable fakeHolidays = new DataTable();
8: // 1. Add Columns
9: fakeHolidays.Columns.Add("Holiday", typeof (DateTime));
10: fakeHolidays.Columns.Add("Name", typeof(string));
11: // 2. Create new DataRow
12: DataRow dayRow = fakeHolidays.NewRow();
13: // 3. Assign values to the row
14: dayRow["Holiday"] = DateTime.Parse("07/04/2008");
15: dayRow["Name"] = "Independence Day";
16: // 4. Add the row to the DataTable
17: fakeHolidays.Rows.Add(dayRow);
18: _pgDate.CompanyDal = dalMock;
19: using (mocks.Record())
20: {
21: Expect.Call(dalMock.GetHolidays()).Return(fakeHolidays);
22: }
23: using (mocks.Playback())
24: {
25: DataTable holidays = _pgDate.Holidays;
26: Assert.GreaterThan(holidays.Rows.Count, 0);
27: }
28: }
I used Rhino.Mocks as my mocking framework in the example above.


