Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a mock Datatable in Unit Testing

Tags:

c#-4.0

I am Unit Testing one of my functions. Here is my code:

public void TestLabels()
{

  //Step 1: Creating a mock table with columns exactly like in the real table.
  DataTable table = new DataTable();

  DataRow mydatarow;
  mydatarow = table.NewRow();

  //Step 2: Adding the row as same as the Real Data!

  mydatarow["Name"] = "Test";
  mydatarow["Address"] = "00000 ST.";
  mydatarow["ZipCode"] = "77665";
  mydatarow["Tracking#"] = "";

  table.Rows.Add(mydatarow);

  foreach (DataColumn column in table.Columns)
    Console.WriteLine(column.ColumnName);

  //Step 3: Call method we are testing.
  var updateTable = IceTechUPSClient.Instance.CreateLabels(table);

  foreach (DataRow row in updateTable.Rows)
  {
    var trackingNumber = row["Tracking#"].ToString();
    Assert.IsFalse(String.IsNullOrWhiteSpace(trackingNumber), "Expecting tracking number generated for every row!");
    Assert.IsTrue(File.Exists(trackingNumber + ".gif"));
  }

}

Now I am getting an error: Column 'Name' does not belong to table. As you can see I have specified column name "Name" here and also added that particular row. Then why I am getting this error? Any help?

Thanks!

like image 943
RG-3 Avatar asked Dec 14 '10 20:12

RG-3


People also ask

Can database be mocked for unit testing?

Yes, absolutely! Because our code that talks to the real DB is already tested carefully in the previous lecture. So all we need to do is: make sure that the mock DB implements the same interface as the real DB. Then everything will be working just fine when being put together.

Is mocking necessary in unit testing?

Mocking is a very popular approach for handling dependencies while unit testing, but it comes at a cost. It is important to recognize these costs, so we can choose (carefully) when the benefits outweigh that cost and when they don't.

How do you mock a data set?

You can mock it like this: IDataInterface di = new Mock<IDataInterface>(); DataSet mockDataSet = CreateMockDataSet(); di. Expect(x => x. Get()).


1 Answers

You haven't set up your columns (unless you've missed out some code in your example).

You need to create the columns with the required names before you can access them like this:

var columnSpec = new DataColumn
                    {
                        DataType = typeof(string),
                        ColumnName = "Name"
                    };
this.table.Columns.Add(columnSpec);

When you read data from the database if you've set AutoGenerateColumns to true (the default) you don't need to do this explicitly as it's done for you behind the scenes.

like image 106
ChrisF Avatar answered Sep 21 '22 07:09

ChrisF