A lot of people (myself included) find the hardest part about Test Driven Development is getting started with it.
It’s usually pretty easy to pick up the fundamental principles of it; write a failing test first, make it pass, refactor your code, check the test still passes etc. but it’s not so easy to actually start writing your own (useful) tests and to shift your development process to fit TDD.
Once of the big hurdles to overcome is dependencies. More often than not you find it’s hard to test just one object, because that object relies on other objects which, whilst you’re not testing them here, you still need to be able to rely on to make your test pass.
This is where mocking comes in.
Rhino Mocks lets you create “pretend” objects which can exhibit all the behaviour you need (to make your tested object work) but without you relying on a concrete implementation of the mocked object.
Mocks go hand in hand with interfaces as it is far easier to mock an interface than a concrete class.
Take the following example…
Here we create mocks of two objects (IVehicleSearchResultsTask, IViewVehicleSearchResultsView).
We can then define an expectation that the method called GetMatchingVehicles will be called (on our mockTask).
We switch Rhino Mocks from record mode into replay mode (in otherwords, we stop defining expectations and start waiting for those expectations to be met) at line 7.
At line 9 we instantiate an instance of VehicleSearchResultsPresenter, passing in our mockView and mockTask as we do.
(for this example, we are presuming that instantiating the presenter should call the GetMatchingVehicles function).
Finally we see if our expectations have been met (Line 10).
This is a great way of ensuring you only test one thing at a time (in this case our presenter).
Download Rhino Mocks from here.comments powered by Disqus