How to Mock an Initialization Method

I have come across this scenario a few times, where developers want to swap a method with another method. Here is a quick example:

Suppose we have an initlization method called FillIt(). This method expects a List and fills it with data (from a database for example)

private void FillIt(List theList) { // connect to database and fill the list }

Now in our test, we don’t want to connect to the database, we want to mock this method but we want to fill the list with fake data. We would actually like to tell TypeMock to call another method instead

private void MockedFillIt(List theList) { // fake data for test theList.Add("Item 1"); }

Well we can’t really do this yet. What we can do is call the DynamicReturnValue delegate that will fill the list for us

Mock theMock = MockManager.Mock(typeof(TheType)); theMock.ExpectAndReturn("FillIt", new DynamicReturnValue(MockedFillIt)); ... // Called when FillIt is called private object MockedFillIt(object[] parameters, object that) { List theList = (List)parameters[0]; // fake data for test theList.Add("Item 1"); return null; // FillIt is void }

Notes:

1. You can use ExpectAndReturn for void methods when the return value is DynamicReturnValue
2. The delegate is executed when the mocked method is called
3. The delegate receives the actuall mocked object (context) and arguments.
4. The return value is ignored for void methods.

QUESTION

Do you think that we should have another API for this scenario?
e.g

theMock.ExpectCall("FillIt").Perform(MockedFillIt);

Add Comment

Required fields are marked *. Your email address will not be published.