Tuesday, 20 October 2009

Testing Objects Without Interfaces Using an Interface Wrapper and a Partial Class

I've found that often I'm using a framework that doesn't lend itself to unit testing very well. In the past I've used wrappers, a class that contains an instance of the object that is not testable and inheriting an interface that I can mock, but this is a lot of work.

A colleague of mine recently came up with a great idea using partial classes. If you create a partial class of your class you wish to mock and have the partial class inherit from an interface then you will be able to mock the interface for testing. All you need to do is create your stubs of any methods you wish to use in your interface and you're away.

It's not quite as clean as if your original object instantiated it's own interface, but it's much cleaner than a wrapper class. I thought that it was ingenious, for some reason I never thought of it. Oddly enough since he thought of it I've been finding implementations of it everywhere. A couple of instances of the idea online and then when I was interviewing a guy the other day, he suggested the same thing as if it was just common sense.

It's really true that there is no such thing as a professional developer.