chevron-thin-right chevron-thin-left brand cancel-circle search youtube-icon google-plus-icon linkedin-icon facebook-icon twitter-icon toolbox download check linkedin phone twitter-old google-plus facebook profile-male chat calendar profile-male
0 votes
In the below example I'd like to change which table is being used for a DataView, so I'd like to just switch the DataSet returned from a constructor for a different one. The third assertion fails. Is this something that's possible to do?

        [Test]
        public void TestContructorMocking()
        {
            DataTable table = new DataTable();
            DataView dataView = new DataView(table);

            using (RecordExpectations recorder = RecorderManager.StartRecording())
            {
                //new DataView(null);
                recorder.ExpectAndReturn(new DataView(null), dataView);
            }

            DataTable table2 = new DataTable();
            DataView dataView2 = new DataView(table2);

            MockManager.Verify();
            Assert.IsNotNull(dataView2.Table);
            Assert.IsFalse(dataView2.Table == table2);
            Assert.IsTrue(dataView2.Table == dataView.Table);
        }
asked by marcus (1.1k points)

1 Answer

0 votes
Hi,

There is special API for specifying a return value from a constructor.
we do have a mechanism for replacing created object during runtime (we call this scenario "mocking a future instance")
you can get more details in this blog post.

Here is an example on how to do it.

public class DataTable
{
    public int ReturnFive()
    {
        return 5;
    }
}
public class DataView
{
    internal DataView(DataTable table)
    {
        _Table = table;
    }

    private DataTable _Table;

    public DataTable Table
    {
        get { return _Table; }
        set { _Table = value; }
    }
}
[TestClass]
public class DataViewTests
{
    [TestMethod]
    [Isolated]
    public void RepalcingDataViewExample()
    {
        /// This will swap the next creation of a dataTable 
        DataTable fake = Isolate.Fake.Instance<DataTable>();
        Isolate.SwapNextInstance<DataTable>().With(fake);
        // setting an expectation of the fake table
        Isolate.WhenCalled(() => fake.ReturnFive()).WillReturn(6);

        //table2 will actualy be mocked.
        DataTable table2 = new DataTable();
        DataView dataView2 = new DataView(table2);

        Assert.IsNotNull(dataView2.Table);
        //calls to DataView2.Table will be mocked 
        Assert.AreEqual(6, dataView2.Table.ReturnFive());
    }
}

:!: For simplicity I've replaced the real DataView and DataTable classes with simple one I've created in the example however the same syntax will work on all classes you use.

Hope this helps let me know if you have anymore questions.
answered by lior (13.2k points)
...