Skip to main content

The role of Mocking in TDD, Test First with Rhino Mocks, KandaAlpha

Recently I got into a healthy discussion with Keith Patton about Constructor Injection and other such topics to do with Test Driven and Domain Driven Design.

One way or another this lead to the birth of Kanda Alpha with the goal of demonstrating best practice domain driven design utilising Visual Studio 2010 Beta, ASP.NET MVC 1.0 and Db4o as the data store.

I’ve decided to give an explanation as to the benefits of Mocking and the Test First approach.

Mocking quite simply allows you to test components in isolation from their dependencies. By mocking out the results and behaviour of the dependent components you can focus on verifying the behaviour of a single class.

Where I’ve found it most useful is in designing the service layer and this is usually the first thing I design after hashing out the Domain Entities.

There has also been some comments on Keith’s blog about the purpose of the Service layer if all it is doing is acting as a Facade to the Repository. This is a valid point and I’m going to try and give a real life example which demonstrates that this isn’t the case. 

From Martin Fowler’s Domain Driven Design

“A Service Layer defines an application's boundary [Cockburn PloP] and its set of available operations from the perspective of interfacing client layers. It encapsulates the application's business logic, controlling transactions and coordinating responses in the implementation of its operations.”

http://martinfowler.com/eaaCatalog/serviceLayer.html

Second only to the Entities Model the Service Layer is the heart of your application so should be the focus of the design and that’s where Mocking will add value.

The example I’m going to demonstrate is the very simple but very common Registration of a User.

When a User is created there are a number of requirements that need to be met:

  • Geocode the Users Address
  • Persist the User to a data store
  • Send an Email asking them to confirm their email

Right so let’s see some code.

Firstly I will define the IRegistration interface

regservice

Ok as we are doing Test first let’s create an Implementation and set up our first Unit Test.

regserviceimpl

Now the Mocking framework of choice is Rhino.Mocks.

So here is the very first Unit Test.

regusertest

Note this test will fail as RegisterUser has not been implemented yet, this is fine as it is failing for a very valid reason.

reguserfail

Because of the requirements listed above the IRegistrationService implementation is going to have dependencies on some other components to fulfil these requirements.

  • IUserRepository
  • IAddressGeocoder
  • IMessageSender

So let’s define those

geoservice

Now we will define the IUserRepository which will be used  to persist the User.

userRep

Finally we need a component to send the confirmation email.

messageSender

Ok now that we have defined the Interfaces for our dependencies, let’s add them to our RegistrationService implementation. For this I am going to use Constructor Injection (link here) it will become clear shortly why.

regwithdependencies

Now that we have obviously broken our test  because there is no longer a default constructor.  So let’s fix up our test so that it runs again.

regservicetestwithmocks

You will notice above that I have used the MockRepository to generate in-memory Stubs. We do this because we don’t want to worry about the implementations at this stage.

Now we need to Setup some results.

regserviceStubs

Now that we have setup our test we can write the implementation, which should be easy. 

reguserimpl

Now running the test should give us the all important green tick.

reguserpass

Well that’s it. By following this approach you are forced to think about how classes interact with other classes and as a result you end up with loosely coupled components that are Unit Testable.

The source code is available to on the KandaAlpha project on Codeplex.

Popular posts from this blog

ASP.NET MVC Release Candidate - Upgrade issues - Spec#

First of all, great news that the ASP.NET MVC Release Candidate has finally been released.  Full credit to the team for the hard work on this.  You can get the download here  However this is the first time I have had upgrade issues.  Phil Haack has noted some of the issues here   If like me you have lot's of CTP's and Add-Ins then you might experience some pain in Uninstalling MVC Beta on Vista SP1  This is the list of Add-Ins / CTP's I had to uninstall to get it to work  Spec# PEX Resharper 4.1  Sourcelinks ANTS Profiler 4   Can't say I'm too impressed as it wasted over an hour of my time.  As it turned out Spec# turned out to be the offending culprit, it's forgiveable to have issues with a third party product but a Microsoft one? Guess no-one on the ASP.NET team has Spec# installed. 

Freeing Disk Space on C:\ Windows Server 2008

  I just spent the last little while trying to clear space on our servers in order to install .NET 4.5 . Decided to post so my future self can find the information when I next have to do this. I performed all the usual tasks: Deleting any files/folders from C:\windows\temp and C:\Users\%UserName%\AppData\Local\Temp Delete all EventViewer logs Save to another Disk if you want to keep them Remove any unused programs, e.g. Firefox Remove anything in C:\inetpub\logs Remove any file/folders C:\Windows\System32\LogFiles Remove any file/folders from C:\Users\%UserName%\Downloads Remove any file/folders able to be removed from C:\Users\%UserName%\Desktop Remove any file/folders able to be removed from C:\Users\%UserName%\My Documents Stop Windows Update service and remove all files/folders from C:\Windows\SoftwareDistribution Deleting an Event Logs Run COMPCLN.exe Move the Virtual Memory file to another disk However this wasn’t enough & I found the most space...

CPF Contribution Rates for new Singapore Permanent Residents (SPR’s)

Recently my wife and I applied and got approved for Singapore Permanent Residency. After completing the formalities the most significant immediate change is the contribution to CPF which is Singapore’s mandatory social security savings scheme requiring contributions from employers and employees. CPF contributions start from the date you obtain SPR status, which is the date of the entry permit.   Being a relentless budgeter I needed to know exactly how much I and my employer would have to contribute so that I could adjust my budget accordingly as the employee contributions get deducted from the monthly salary. After doing some research I discovered that there is a “graduated” approach to CPF contributions for new SPR’s where the contributions gradually increase in the first and second year and then upon reaching the third year are at the full amount. Note: There is an option for employers to contribute the full amount for year 1 and year 2 and the employee can use the gra...