Write Just One Test

To avoid being overwhelmed by UnitTests focus on getting them running one at a time.

TestFirstDesign sounds good in theory, but in practice it can lead to a sort of AnalysisParalysis where it seems like all you are doing is writing more and more UnitTests none of which work and most of which don't even compile.

This is usually caused by trying to test too much at one time. Sometimes the tests reflect some up-front design, sometimes they come about because of a recursive sequence of tests each motivated by functionality needed by the last. In the end you wind up with lots of assumptions and lots of tests but no feedback and no working code.

Therefore:

Throw all the tests away and start with only one. If that one can't be satisfied quickly then throw it away and come up with a simpler one. Never have more than one test active at a time. If in the course of satisfying one test you find that you need another then write down the name of the first test, throw it away, and write the second.

If you do this the insurmountable mountain of tests will go away and will not come back. Most functionality will be easy to implement this way, but some things may defy your efforts to simplify them. Some problems want to be solved through collaboration, for instance. Others want to be decomposed into layers of functionality each building on the layer below. If you keep the names of the tests you've thrown away during your efforts at simplification in a list then you can go back up the list, writing tests as you go, until you get back to the test that you originally wanted to write. This will solve most decomposition problems (although it's better for layers than it is for collaborations). You will need to refactor lower layers in response to feedback that you receive from implementing higher layers but you will have the lower layer tests to help you and you will be responding to real feedback rather than speculation. Sometimes the complexity brought on by the need for collaboration can be managed by using MockObjects. It may seem wasteful to throw away the higher level tests rather than just commenting them out, but it keeps the focus on a single level at a time and allows each test to be written with the maximum amount of information.

The bit about throwing away tests and keeping their names on lists might stand on its own as a separate pattern. Other patterns relating to WriteJustOneTest are MockObject as mentioned already, and TestToComfort? which deals with the issue of just how many tests to write.

See also OneUnitTestAtaTime


CategoryTesting


EditText of this page (last edited February 16, 2005) or FindPage with title or text search