Introduction
With Test-First Design (TFD) you do detailed design in a just-in-time (JIT) manner via writing a single test
before writing just enough production code to fulfill that test. When you have new functionality to add to your
system, perform the following steps:
-
Quickly add a test. You need just enough code to fail.
-
Run your tests. You will typically run the complete test suite, although for sake of
speed you may decide to run only a subset. The goal is to ensure that the new test does in fact
fail.
-
Update your production code. The goal is to add just enough functionality so that
your code passes the new test.
-
Run your test suite again. If they tests fail you need to update your functional code
and retest. Once the tests pass, start over.
Why TFD?
A significant advantage of TFD is that it enables you to take small steps when writing software, which is not only
safer it is also far more productive than writing code in large steps. For example, assume you add some new functional code, compile, and test
it. Chances are pretty good that your tests will be broken by defects that
exist in the new code. It is much easier to find, and then fix, those
defects if you've written five new lines of code than in fifty lines. The implication is that the faster your compiler
and regression test suite, the more attractive it is to proceed in smaller and smaller steps.
There are three other common testing strategies (in order of effectiveness).
-
Write several tests first. This is a variant of TFD where you write more than one test
before writing just enough production code to fulfill those tests. The advantage is that you don't need to
build your system as often, potentially saving time. It has the disadvantage that you will write
more production code at once, increasing the difficulty of finding any new bugs that you do introduce.
-
Test after the fact. With this approach you write some production code then you write enough
testing code to validate it. This has the advantage that you're at least still validating the code but has
the disadvantage that you lose the design benefit inherent in writing the testing code first.
-
Don't test at all. This is a really bad idea.
Good Things to Know
1. An underlying assumption of TDD is that you have a unit-testing framework available to you. Agile software developers often use the xUnit family of open source tools, such
as JUnit or VBUnit, although commercial tools are
also viable options.
2. Test-Driven Design (TDD) = TFD + Refactoring
3. TFD/TDD is commonly used with object-oriented business code, although you can also take this approach with
procedural code, user-interface code, and your database code if you choose to.
4. A more thorough discussion of TFD and TDD is presented at Introduction to Test Driven Development (TDD).
|