Breaking Down a Unit Test from "Reggie" That Uses MoQ
April 21, 2012
Test driven development is hard. Perhaps it would not be if we were taught to think about OO development from a TDD perspective in the first place; but those muscles are poorly developed, and the exercise leaves you sore and panting a bit. As with physical exercise, there is a reward in the pain. Perhaps others do not see it, but I can already see the benefits accruing in Reggie as I rebuild it with SOLID principles in mind, driven by tests. To help me consolidate where I’m going, and help others whose TDD muscles are likewise under-developed, let us walk through a test, shall we?
First, some context. I’m working on adding persistence to the application: ability to save and re-open session data. I have a ViewModel, called ReggieBasicViewModel
, which initially contains the data to persist and which binds the View to my business logic. The ViewModel is being instantiated with a factory object, which allows the ViewModel to build concrete instances of various dependencies. This illustrates the Abstract Factory pattern, and the Open-Closed Principle, but arguably violates Single Responsibility Principle [same link as OCP] by grouping un-related functionality into the factory. The proper factory object is configured in the application’s bootstrapper class, or or it is setup in a unit test using an alternate factory implementation.
I’d like to save to / retrieve from an XML file. But what if my requirements change in a few days? I’m told to save to a database, or a web service. It would not be wise to design for that – but I can easily make the system flexible enough to handle addition of other types of persistence in the future. So I create an interface in my business layer, called ISessionPersistence
. As you can see, I’ve added a factory method to the IHelperFactory, for building an instance of ISessionPersistence
.
The method SaveSession
in ReggieBasicViewModel
does not yet have a body. It will need to execute the Save method in the persistence layer. First things first: a unit test.
[TestMethod] public void SaveSessionLoadsSessionIntoPersistenceService() { // Prepare Input