Five Unit Test Tips: #1: Use the data store

I’ve looked over some of my code lately, and found ways that I often improve my tests. I’m planning on writing a blog post for each of my five favorites.

First out: Using the data storage. I upgraded our API for billing customers. I had a few compilation errors in my code, as the API had changed somewhat. After fixing these errors, I was left with a test that broke mysteriously with a MethodNotFoundException. I located the test and found that it was close to unreadable. After examining it further, I found that it was trying to do was simple, but hidden in technical code.

I had the following test (the design is real, the details have been changed to protect the guilty):

When the parameters to sendBillingEvent changed and the test started throwing MethodNotFoundException I changed it to the following:

The lessons:

  • Ask about the outcome, not about the method calls that get you there
  • Avoid reflection in tests. It’s bound to be brittle
  • Mocks and similar methods are overrated

(In tip #2, I will show how I preserve the data store metaphor without giving up execution speed)

Copyright © 2008 Johannes Brodwall. All Rights Reserved.

About Johannes Brodwall

Johannes is Principal Software Engineer in SopraSteria. In his spare time he likes to coach teams and developers on better coding, collaboration, planning and product understanding.
This entry was posted in Extreme Programming, Java. Bookmark the permalink.

Comments are closed.