Friday, August 25, 2006

A lot of people want to use mock objects in their code, but have a hard time because of the steep  learning curve it takes to learn how to use mock objects.

Today at work, I accidentally stumbled upon an easy way to learn the syntax of Rhino Mocks. Keep in mind that this is not the proper way to do test driven development, this method should only be used to understand the Rhino Mocks way of doing things.

Say we have a presenter class which needs to call another layer in order to do it's work like so:

Public Sub Save() _task.UpdateSettings() End Sub

 This is a pretty contrived example but it helps get my point across. In order to see what Rhino Mocks is expecting to happen you can set up an empty test like this:

Dim _mockery As MockRepository = new MockRepository _task = CType(_mockery.CreateMock(GetType(ISettingsTask)), ISettingsTask) _mockery.ReplayAll() _presenter.Save()

Now when you run the tests, Rhino will tell you that it expected the task layer to get called when the save method in the presenter was invoked. You can satisfy Rhino with the following code:

Dim _mockery As MockRepository = new MockRepository _task = CType(_mockery.CreateMock(GetType(ISettingsTask)), ISettingsTask) _task.UpdateSettings() LastCall.IgnoreArguments() _mockery.ReplayAll() _presenter.Save() _mockery.VerifyAll()

Once you get the hang of Rhino's syntax and how it works you can change your mindset and do the code here in reverse with red, green refactor and you will reach mocking zen. If you have any questions please leave a comment or email me and I will try my best to answer it.

 Update: Mike, let me know this morning that I was missing a VerifyAll() after my _presenter.Save(). I take it for granted because I have it in my TearDown but I have added it for clarity.

[ Currently Playing : Oh, Me - Nirvana - MTV Unplugged in New York (03:26) ]

Friday, August 25, 2006 5:20:30 AM (GMT Standard Time, UTC+00:00)  #    Comments [2]  | 

Theme design by Jelle Druyts

Pick a theme: