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);

Bookmark at:
Add 'How to Mock an Initialization Method' to Del.icio.us Add 'How to Mock an Initialization Method' to digg Add 'How to Mock an Initialization Method' to reddit Add 'How to Mock an Initialization Method' to Feed Me Links! Add 'How to Mock an Initialization Method' to Technorati Add 'How to Mock an Initialization Method' to Yahoo My Web Add 'How to Mock an Initialization Method' to Newsvine Add 'How to Mock an Initialization Method' to FURL Add 'How to Mock an Initialization Method' to blinklist Add 'How to Mock an Initialization Method' to My-Tuts 

21 January 2007 | .NET Tests | Comments | Print This Post

Leave a Reply

  1.  
  2.  
  3.  
Search Eli Lopian’s Blog (TypeMock)

Navigation

Recent Posts

Categories

Archives

Managment