I am very bad at writing tests

… but I _think_ I might be getting a little better.

At least these days when I am writing some script (almost certainly in [Python][python]) I start out by intending to write tests. I usually fail because I haven’t learnt to think in terms of writing code that can be easily tested.

[Mark Pilgrim][pilgrim]’s [Dive Into Python][dive] has great stuff on how to approach a problem by [defining the tests first and gradually filling in the code][divetest] that satisfies the test suite. One day I may be able to work like that, until then I work by writing a concise docstring, then stubbing out the function. Once the function is in a state where it might actually return a meaningful result I can play with it in the Python interpreter and start adding useful [doctests][doctest] to the [docstring][docstring].

What really helps is to break the logic out into tiny pieces where ideally each piece returns the result of transforming the input (which I think is known as a [functional approach][functional]). By doing this I can have tests for most of the code and those functions that have a lot of conditional logic, those functions that are harder to write tests for, will at least be relying on sub-routines that are themselves well tested.

I can dream.

[python]: http://www.python.org/
[pilgrim]: http://diveintomark.org/
[dive]: http://www.diveintopython.org/
[divetest]: http://diveintopython.org/unit_testing/stage_1.html
[doctest]: http://docs.python.org/library/doctest.html
[functional]: http://en.wikipedia.org/wiki/Functional_programming
[docstring]: http://www.python.org/dev/peps/pep-0257/

Leave a Reply

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