Ian Cooper recently wrote about the Ratio of test code to production code. Ian is saying that he's routinely seeing a 1:1 or even 1.5:1 ratio of test code to production code. From my experience with TDD, that's about normal. Some kinds of code will go even higher. For example, any kind of significant recursive functionality will make the ratio go throught the roof (a Visitor/Composite pattern combo is central to StoryTeller. That jacks up the test code LOC relative to the real code LOC significantly).
All I want to add to Ian's post is that that number should not discourage newcomers to TDD. All those lines of code are not created equal. Unit test code does not take anywhere near the same amount of concentration or care as production code. I say that mainly because unit test code is composed almost entirely of stand alone methods. They don't interrelate or interract with each other. The responsibility of a unit test is almost always the same: setup data, do something, check the results. The hardest thing about coding is deciding what to code, not the mechanical act of typing. The hard part of writing a unit test is deciding what the real code is supposed to be doing , then codifying that specification in the unit test. Since you'd be doing that specification work in your own head or a document anyway, all you've added is the mechanical work to type it out in a unit test method.
TDD is cost effective when and if the effort you put into writing the tests is less than the corresponding effort would have been for the manual unit testing and additional debugging that you dodge by having comprehensive unit test coverage. Add in the hard to quantify advantage from the qualities of orthogonality that TDD all but requires (testability design is mostly about creating orthogonality between the pieces). Plus, if you're good, time spent TDD is also time spent doing design in the small and hopefully creating a useful and human readable set of documentation about the fine grained details of the code.
And while I'm thinking about it, the whole "Who tests the tests" issue?
A.) Keep your unit tests as simple, concise, and readable as possible to help catch problems by inspection
B.) Just pay attention to what you're doing
C.) What Phil Haack said in the link above about the code testing the tests and vice versa. I find most unit test bugs when the test fails and the code seems perfectly right.
Posted
Thu, Mar 22 2007 3:45 PM
by
Jeremy D. Miller