Recently I ran across a situation where I was using an object from a third party ORM tool that I wanted to mock for unit testing. The method I wanted to test uses this particular third party object and calls methods on it that interact with our data store. I just wanted to test my method and ensure it calls this third party object correctly, I don’t want the third party object to actually be called since it would then attempt to do its business of communicating with the application’s data store. The problem was that the object does not implement any interface I can use to easily mock it through a mocking facility such as rhino mock. Some mock facilities, such as rhino mock, will let you mock an actual object if the methods you want to call are virtual and can be overridden. Unfortunately the methods I was interested in aren’t virtual so can’t extend the object and create a child class mock without having the real base methods fire. This wouldn’t work since it was just those methods I wanted to fake.
I think I came up with a fairly slick solution, and a friend even told me this is the same solution proposed by Robert Martin in his book ‘Working With Legacy Code’, when encountering this situation. All the classes and code below are only examples, they aren’t the code I was actually working on, there would be too much to explain if I tried to actually use that!
The class I want to mock is named ‘UnitOfWork’. In order to create a type I can use for abstraction I created an interface, ‘IUnitOfWork’ that reflects all the methods in the class that I’m interested in mocking. Continue reading “Mocking Closed Objects”