Monday, July 12, 2010

If it's hard to test, look at the design

I was reading recently about a clever technique to verify that a series of calls to a mock object occurred in the correct order. The calls were passing items from a sorted list to a mock view object, and the author was trying to test that the list was sorted correctly.

foreach (Widget widget in sortedWidgetList) view.Show(widget);
The fact that it was difficult to verify the order of calls should first make us wonder if there is a problem in the design, before we look for clever ways to write the test.

Depending on the order of calls indicates a temporal coupling between the classes under test. It means the target of the calls probably has to maintain some kind of state between the calls. These are things we'd like to avoid if we can.

In this case, the solution is simple: pass the sorted list to the view in a single call, rather than passing each item separately in a series of calls.

view.Show(sortedWidgetList);
Now our test is easier to write, and our code is cleaner. The test told us what to do.

1 comment:

  1. Great thoughts Mike. Love the design of the second option compared to the first. Your experience and testing savyness help here too.

    Cheers - JR

    ReplyDelete