Retro Fitting Unit Tests to Legacy Code

This post references a StackOverflow thread which you can read
here

One of the problems with TDD is that those who try it, often begin by booting up NUnit or something similar, writing a few trivial tests to get the lie of the land, then instead of doing TDD (i.e. Writing a test and then writing some code to make the test pass) they do something much much harder, under the mistaken impression that it will actually be a way to ease themselves into TDD.

They do what I did, they start out by trying to write some unit tests for existing code. Either a past project, or more likely the project they are currently working on. They quickly discover that these projects are (from their perspective) virtually impossible to test.

The reason why is obvious, 1) They are new to writing automated tests, which is a tricky enough skill to master, but more importantly 2) They are new to writing testable code which is actually a significantly bigger challenge than writing tests. The chances that their old projects contain testable code is virtually nill.

So, our protagonist is actually starting their journey to TDD with an obstacle that is actually beyond the ability of some seasoned TDD practitioners. Think a video game with the ultimate Boss level as the very first thing you do, before you learn the controls or understand much of anything about the game. That right there is a game that you’ll probably throw in the bin after about an hour, if you last that long.

In my research for my TDD session at #dddsw I found lots of interesting questions, blogs and articles, most of which I didn’t have time to fully discuss during the session, but I’ll point you in the direction of some of them over the next few days/weeks.

The first is a Stack Overflow discussion on how to write automated tests for a complicated function with lots of dependencies.

It’s notable because it’s not an uncommon problem, and the answers cover the usual spectrum from practical solutions to pragmatic advice to questioning the validity of the original question etc.

It’s also notable because Uncle Bob contributes an interesting Step By Step on how to add tests to existing code (in an kludgy way) and then how to refactor both the original code and the kludgy test handling.

Original Thread Here

Enjoy.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Switch to our mobile site