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.

Comments

  1. nice post will, will take a look shortly;) keith

    ReplyDelete

Post a Comment

Popular posts from this blog

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\TempDelete all EventViewer logs Save to another Disk if you want to keep themRemove any unused programs, e.g. FirefoxRemove anything in C:\inetpub\logsRemove any file/folders C:\Windows\System32\LogFilesRemove any file/folders from C:\Users\%UserName%\DownloadsRemove any file/folders able to be removed from C:\Users\%UserName%\DesktopRemove any file/folders able to be removed from C:\Users\%UserName%\My DocumentsStop Windows Update service and remove all files/folders from C:\Windows\SoftwareDistributionDeleting an Event Logs Run COMPCLN.exe Move the Virtual Memory file to another disk However this wasn’t enough & I found the most space was cleared by using the Disk Cleanup to…

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 graduated rate, b…

Consuming the SSRS ReportExecutionService from a .NET Client

I’ve just finished writing a nice wrapper which internally calls the SSRS ReportExecutionService to generate reports.
Whilst it was fairly simple to implement there has been some major changes between 2005 and 2008 and the majority of online and documentation is based on the 2005 implementation. The most important change is that the Report Server and Report Manager are no longer hosted in IIS which will be a welcomed change to Sys Admins but makes the security model and hosting model vastly different. So far I’ve yet to figure out how to allow Anonymous Access, if anyone knows how to do this leave a comment and it will be most appreciated. Getting StartedTo get started you’ll want to add a service reference to http://localhost/ReportServer_SQL2008/ReportExecution2005.asmx where ReportServer_SQL2008 is the name you configure in the Reporting Services Configuration Manager. The Web Application files are located in C:\Program Files\Microsoft SQL Server\MSRS10.SQL2008\Reporting Servic…