Thursday, April 19, 2007

Classicist or Mockist Test Driven Developer

I just read an interesting article titled "Mocks Aren't Stubs", by Martin Fowler. In this article, he explains the difference between a Classicist and Mockist TDDer (Test Driven Developer). After reading the article, I started to reflect on the TDDer style I have been practicing and if I needed to reevaluate my strategy.

When I first started practicing TDD, I didn't use Mock objects. Instead, I relied heavily on Dummies and Stubs. If I was unit testing object A that collaborated with object B, then I would have a stub implementation of B that had states that could be set. For instance, if I was testing method A.calculatePay(), that called B.getHourlyRate() that returned a Float, then the stub implementation of B would have a method called setHourlyRate() giving me the ability to control what was returned from the B.getHourlyRate() method. This approach did meet my needs, although it really cluttered up my testing package and the stubs soon became very messy. Imagine if B.getHourlyRate() returned a Float but also had the possibility to throw 3 different types of exceptions that should be handled differently in object A. If this was the case, I had a very complicated stub implementation of B in order to control whether to return the Float or throw 1 of the three exceptions. By doing this, I found myself writing more code to control the behavior of the stub implementation rather than testing A.calculatePay().

After I became familiar with mock frameworks, it really simplified my unit tests. Instead of creating a stub implementation of B, and programmatically controlling it's behavior, I leveraged a mock object framework that did most of the work for me. The Tests with Mock Objects portion of Martin Fowler's article shows examples of how this can be accomplished. What I found was an increase in productivity because I was no longer focused on building stub code to handle all of the different cases, but actually working on testing A.calculatePay().

Ultimately, whether you call yourself a Classicist or Mockist TDDer, in my opinion, as long as you are practicing TDD, you are on the right path.

No comments: