Mocks vs Stubs


I’ve been using Rhino Mocks for a while on my current project, and recently came across a few articles weighing up the pros and cons of mocks vs stubs. To me, I don’t get what the fuss is about within the context of a unit test. Most if not all our unit tests follow the AAA pattern. So I might have something like:

// Arrange

var dbLayer = MockRepository.Stub <IDbLayer>();

var customers = new List <Customer> ();

dbLayer.Stub (db => db.LoadCustomersByRegion(1)).Returns (customers);

// ... register into e.g. Unity etc. 

 

// Act

var myServiceLayer = new ServiceLayer ();

var result = myServiceLayer.GetCustomersForRegion (Regions.Uk);

 

// Assert

dbLayer.AssertWasCalled (db => db.LoadCustomersByRegion (1));

Assert.AreSame (customers, result);

This sort of approach seems fairly logical – to me – and easy to read i.e. creation of stubs and setting what methods will return is done at the start of the unit test. Assertions are at the end of the unit test.

However, I’m reading other people using Replay, Expect and VerifyAllExpectations etc. etc.. Martin Fowler’s definition of stubs seems to be the “classical” definition of what a stub is i.e. typically a method which is written to return some hard-coded values in absence of “real code”. However, in the context of unit tests like that above, stubs effectively become mocks.

I’ve read a few articles scattered around on people commenting on how using stubs in the above manner is “wrong” and that one should never place expectations on stubs – why not? It all works to me – and frankly it reads more logically than the Reply / Expect mechanism.

However, as someone who is a relative newcomer to using mocking frameworks (maybe the last six months of using it in anger) maybe I’m missing something here – please feel free to tell me 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s