Testable Object pattern

UnitTests should be given the same level of respect and care that we put into writing production code, if it is not readable and maintainable then you might as well remove it.  I’ve always struggled with refactoring test code that contains mocked objects that I want to invoke some method on within my tests.  This is until I came across Brad Wilson’s testable object pattern, which really gave me that ah-ha moment.  It is simple to create and easily readable which is the perfect combination.  However, you still have to do the dirty dance of determining the fine balance between how much refactor you want to do as opposed to it still being readable.

Assume that you’ve a bunch of test that looks something like this:

oldtest

Creating the mock objects and inserting them into the PromoController seems pretty redundant if you’ve to do it more than a few times.  The way you refactor it is by creating a new class that inherits the class that is being tested (in my case PromoController) and it exposes the two mocked objects as its fields.

testableObject

You can make the two mocked fields as auto-properties if you like but when dealing with tests, I try to avoid it because it adds more noise to the code without giving me any benefits.  Now, the previous test can be refactored using this new TestPromoController class while still having access to its mocked objects.

newtest

Happy Summer! Mug