Question

Using Microsoft Fakes Framework, I am working on a Unit Test that tests a method for inserting a record. I have three classes: TransportControllerTest, TransportManager and DbController. The TransportControllerTest is the Unit Test class. The TransportManager is part of the Business Logic Layer and the DbController has three methods (insert, get and delete). These last methods access my database using ADO.NET.

In my Unit Test I want to test the insert method of TransportController. This controller calls the dbController twice: dbController.insert() and dbController.get(). The last call gives the last generated key by passing the parameters used to insert in the first call. So in TransportController, I can access the generated id by calling:

    string val = dt.Rows[0]["id"].ToString();
    int id = Int32.Parse(val);

I want to mock the value above, so this expression is true:

    dt.Rows[0]["id"].ToString().Equals("*mocked id*");

I have tried the following:

    DataTable dt = new DataTable(dataSetName);
    dt.Columns.Add("id");
    DataRow dr = dt.NewRow();
    dr.ItemArray.SetValue(1, 0);
    dt.Rows.Add(dr);

    return dt;

But this doesn't work. How can I make the given expression to be true in my test?

Was it helpful?

Solution

Just checked out what you can fake around here.

var row = new ShimDataRow().Instance;

ShimDataRowCollection
  .AllInstances
  .ItemGetInt32 = (collection, i) => row;

ShimDataRow
  .AllInstances
  .ItemGetString = (dataRow, s) => "*mocked id*";

You might consider also mocking the datatable and such if needed, since that would allow you to avoid fetching an instance from the shim.

This way you completely avoid dealing with the System.Data types, and get on with your logic.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top