Saturday, 9 December 2006

More on Test Driven Development

My last post really didnt finish on what TDD means to me. True, I mentioned automated testing which is a useful part of TDD. But bcwhite (thanks for the comment) mentioned the distinction of writing your tests up front vs automating your tests. I do write some of my tests up front ... but you can't always write all of them. I find myself adding more tests as requirements change (or as I think of them).

TDD means writing your code while being mindful of the need to test it. You write your code to expose properties or return values that can help you test. This way you can simulate Input in/Output out and check whether an Exception occurred yes/no, etc.

Also, for your "composite" functions which have connections to units that you don't want to test, (i.e. a component which communicates with a singleton object that you don't need/don't want to test, or a component which uses threading or sockets) you factor your code in such a way that you can test your "units" in isolation of everything else. If you can't easily separate out your unit from everything else, you expose a boolean property called "TestMode" and only set this during automated testing. For each line of code in your unit that you don't want to test during unit testing, you check this boolean first i.e.

If (not TestMode)


If(not TestMode)

The candidate function I mention above is a component which does have inputs/outputs and exceptions thrown but also communicates with a singleton object that passes data to and from an open socket connection. In this case, I want to test the inputs and outputs and exceptions (without communicating with the singleton object).

This makes it much easier to have as much of your code unit tested as possible. Anything beyond a unit no longer becomes unit testing. Thinking this way makes it easier for you to test your code and helps guard your code against the likelihood that changes in requirements will yield undesirable results. In the case where your some or all of your unit tests fail, you know then and there that you have some work to do.

No comments: