A new project and a new pile of legacy code always presents me with a large psychological barrier: where should I begin testing, and where should I begin trying to understand what’s where?
Bill Wake, in the Planning Game Simulator chapter of his Refactoring Workbook, has a great answer. Bill suggests that we begin by writing just one test – any test – for every class in the system. The tests can be as simple as you like; their only purpose is to break the ice. Not only do these tests get every class into the test harness, they also prove to me that it’s possible to get every class under test – and that removes the psychological barrier completely. From there it is always a lot easier to continue writing more tests.
I saw this effect for real recently on a client project, and we also experienced it at this month’s AgileNorth coding dojo. We wanted to refactor a smell away from some of the “GUI” code in Wake’s planning game simulator exercise, and someone suggested we needed to make the refactoring safe by writing a test first. But this was GUI code, so the temptation was to shrug and claim it was impossible. Undeterred, Guy wrote a couple of lines that created the window, pushed a button and checked the resulting number of cards in the backlog, and suddenly we were off and running. The refactoring we had in mind was now safe, and the code now seemed like it was ours.
At that point another interesting effect occurred. We looked at the few tests we now had, and we saw smells in the product code – smells we hadn’t seen when we reviewed it at the start of the evening. The test code was revealing usability smells in the class’ interfaces, and our understanding of what to do and where the code wanted to go deepened.
Even a two-line test can have a dramatic impact on the stress of dealing with “untamed” code.