Monday, February 02, 2009

Test Driven Design examples

I had a post planned out to cover TDD in some detail, but I got about halfway into it when I realized that since I don't get to do enough of it, I'd be better off (actually, you'd be better off) if I pointed you at someplace where it gets done more often, recent events notwithstanding.

Two of the big problems I have with TDD are
  1. How to get started on a project with it, and
  2. How to get it going if you've got a mess of code already

Now, some languages make it a little easier - Java and Python, for example, allow you to add a main() to every file, so that you can invoke each class with a set of test parameters from the start.  This will serve to bootstrap your test scaffolding in most cases, since you can make all your classes callable from their own main(), and have some tests there.  As your application grows, you can eliminate the test main() from more of the classes as you pull methods into patterns, allowing you to move the tests from the original file to the new one.

If you're using C++. however, you're in a bind.  You can't have more than one main, and you need it for your actual program.  A way around this is to make a class that is the core of the process, and have the main() be a shell, calling the constructor of that class, and possibly a start method, as the whole of the function.  Again, as your codebase grows, you can move the test code around as necessary.

If you've got a mess of code already, with now tests, your best bet is to start with the interfaces.  Anywhere there is a API - RPC, SOAP, TCP/IP, etc - you can write a program to provide either end of the connection, and start building a test harness from that.  Use scripts to run the basics, testing every message with good and bad data.  If you have an API at each end of the process, you can connect both end to a single program to allow it to confirm success/failure of any given message.  A tool like netcat can be useful for this - your individual test programs can have a socket sending text datagrams to each other with results.

A caution - this can get interesting enough to consume all your spare time - it's a lot more fun to make things that you can see working than to be wading through spaghetti code that needs  refactoring but lacks tests for checking functionality, so enforce some limits on your test scaffold building, unless you have a mandate from your management to build the test sets.




Technorati Tags --
, , ,
HTTP

No comments: