Programming Search⌘K

Conceptcore

Test-driven development

Also called TDD, test-first development, red green refactor, behaviour-driven development, BDD.

Test-driven development writes a failing automated test before each piece of code, makes it pass with the least code, and then removes duplication. The cycle is red, green, refactor.

Applies to
core-languages

Idea

Test-driven development (TDD) puts the test before the code. Kent Beck states it as two rules in the preface of his book. First, write code only when an automated test fails. Second, remove duplication.1 The rules give an order to the work, and Beck names its three steps red, green and refactor:1

  1. Red. Write a small test that does not work. At first it may not even compile.
  2. Green. Make the test pass quickly. Any shortcut is allowed in this step.
  3. Refactor. Remove the duplication that the shortcut made.

Red and green refer to the bar of the test runner, which is red when a test fails. After the first test of chapter 3, Beck writes: "The bar turns obligingly red."1 Beck gives the goal of the practice with a phrase that he credits to Ron Jeffries: "clean code that works".1 The test does two jobs. It says what the code must do before the code exists, and it checks the code after every change.

TDD is an order of work, not a kind of test. The tests it makes are mostly unit tests, and that page covers how to write them and how a runner finds them. This page covers the cycle that writes them.

The running example on this page is a function that says if a year is a leap year. RFC 3339 defines the rule: a year is a leap year if 4 divides it, except that a year that 100 divides must also be divisible by 400.2 So 2024 and 2000 are leap years, and 2023 and 1900 are not.

The first step is red. The test calls is_leap, and is_leap does not exist yet. In Python the test fails when it runs, with a NameError.

This code raises NameError, on purpose.

# Red: the test comes first, so is_leap does not exist yet.
def test_2024_is_leap():
    assert is_leap(2024)


test_2024_is_leap()

The second step is green, with the least code that passes. Beck calls a constant in place of the real computation Fake It. In chapter 3 his first equals method returns true and nothing else.1

def is_leap(year):
    return True  # Fake It: a constant passes the one test that exists


def test_2024_is_leap():
    assert is_leap(2024)


test_2024_is_leap()
print("1 test passed")
Output
1 test passed

The fake is wrong, and the programmer knows it. The next test shows it. A test for 2023 fails with an AssertionError, and the cycle starts again at red.

This code raises AssertionError, on purpose.

def is_leap(year):
    return True


def test_2024_is_leap():
    assert is_leap(2024)


def test_2023_is_not_leap():
    assert not is_leap(2023)


test_2024_is_leap()
test_2023_is_not_leap()

How it works

The to-do list

The cycle works from a list of tests that the code will need. In chapter 3, Beck keeps such a to-do list next to the code. He adds hashCode() to it when he sees that equals() needs it, and he adds "Equal null" and "Equal object" when he finishes equality, because they are "not necessary at the moment".1 Each cycle takes one item from the list. An idea that comes up in the middle of a cycle goes onto the list, so that the cycle stays small.

For the leap year, the list has four items: 2024 is a leap year, 2023 is not, 1900 is not, and 2000 is. The order matters. Each item adds one part of the rule, so each test fails for one reason.

Three ways to get to green

Beck uses three strategies to get to green: Fake It, Triangulation and Obvious Implementation. The index of his book lists them under the green bar patterns, together with a fourth pattern, One to Many.1

  • Fake It. Return a constant that passes the test. Then change the constant into a variable, step by step, as the refactor step removes the duplication between the test and the code.
  • Triangulation. Generalize only when two or more examples force it. Beck calls it "the third and most conservative implementation strategy". He writes that "we only generalize code when we have two examples or more".1 The test for 2023 above is the second example that forces the constant to go.
  • Obvious Implementation. When the general code is clear, write it. Beck writes that he uses Triangulation "only when I am completely unsure of how to refactor". When he can see the general solution, he writes it at once.1

The program below replays the whole cycle for the leap year. Each row adds one test or changes the code, and the program runs every test that exists at that point. A row ends red when one test fails and green when all pass.

TESTS = [(2024, True), (2023, False), (1900, False), (2000, True)]

# Each version of the code, in the order the cycle writes it.
CODE = [
    ("return True", lambda y: True),
    ("y % 4 == 0", lambda y: y % 4 == 0),
    ("y % 4 == 0 and y % 100 != 0", lambda y: y % 4 == 0 and y % 100 != 0),
    ("... or y % 400 == 0", lambda y: y % 4 == 0 and y % 100 != 0 or y % 400 == 0),
]

# (number of tests, version of the code) for each row of the cycle.
STEPS = [(1, 0), (2, 0), (2, 1), (3, 1), (3, 2), (4, 2), (4, 3)]

for n, v in STEPS:
    text, is_leap = CODE[v]
    failed = [y for y, want in TESTS[:n] if is_leap(y) != want]
    result = f"red: {failed[0]}" if failed else "green"
    print(f"{n} tests  {text:<30} {result}")
Output
1 tests  return True                    green
2 tests  return True                    red: 2023
2 tests  y % 4 == 0                     green
3 tests  y % 4 == 0                     red: 1900
3 tests  y % 4 == 0 and y % 100 != 0    green
4 tests  y % 4 == 0 and y % 100 != 0    red: 2000
4 tests  ... or y % 400 == 0            green

Each red row names the year of the test that failed. Each code change fixes that test and keeps the earlier tests green. The fake goes when the second example arrives, and each later test adds one clause of the rule.

Refactor

Green is not the end. The code that passes is often the first code that came to mind, and it can repeat itself. The third step removes the duplication and keeps every test green.1 Suppose that the cycle reached green with one if statement for each clause of the rule, as in is_leap_before below. The refactor turns the statements into one expression, the same one that RFC 3339 gives in its Appendix C.2 The tests do not change. They run against the old code and the refactored code, and a second check compares both on every year from 1 to 4000.

def is_leap_before(year):
    if year % 400 == 0:
        return True
    if year % 100 == 0:
        return False
    if year % 4 == 0:
        return True
    return False


def is_leap(year):
    return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)


TESTS = [(2024, True), (2023, False), (1900, False), (2000, True)]

for version in (is_leap_before, is_leap):
    for year, want in TESTS:
        assert version(year) == want, (version.__name__, year)
    print(f"{version.__name__}: {len(TESTS)} tests passed")

same = all(is_leap_before(y) == is_leap(y) for y in range(1, 4001))
print("same result for years 1 to 4000:", same)
Output
is_leap_before: 4 tests passed
is_leap: 4 tests passed
same result for years 1 to 4000: True

A refactoring changes the structure of the code and keeps its behaviour. Extract function is one example. The tests are what make the change safe. If a refactoring breaks a rule that a test checks, the test turns red at once, and the last change is the cause. This is why the steps are small. After a change of five lines, the cause of a failure is in those five lines. After a day of changes, it can be anywhere.

What red proves

Red is not a formality. A test that fails before the code exists shows two facts. The test runs, and it can fail. A test that has never failed may not test anything: it may not run at all, or its check may be true for every program. The pitfall below shows such a test.

In languages

LanguageVerdictNote
PythonStandard library
C++Library
JavaLibrary
CIdiom
C#Library
JavaScriptStandard library
TypeScriptStandard library
GoStandard library
RustNative
KotlinLibraryThe Kotlin standard library has no test runner; kotlin.test is a separate library that runs on JUnit or TestNG. Alternative: Kotlin.test or JUnit Jupiter, run by Gradle or Maven; the first red is a compile error for an unresolved name.
SQLLibraryStandard SQL has no test framework. Alternative: PgTAP for PostgreSQL, tSQLt for SQL Server, or queries that compare results with expected rows.
BashLibraryBash has no test framework; a test is a script that checks exit statuses. Alternative: Bats-core, or a script with set -e and the test command.
PowerShellLibraryPowerShell has no test framework in the language or its core modules. Alternative: The Pester module, with Describe, It and Should.
HTMLDoes not applyMarkup has no units to call; it is tested through a browser.
CSSDoes not applyStyle rules have no units to call; they are tested through a browser.
Regular expressionsDoes not applyA pattern is tested through the language that uses it.

The cycle is the same in every language. What changes is the first red. In a language with static type checks, a call to a function that does not exist stops the compiler, so the first red is a compile error. In a dynamic language, the program starts and fails when the call runs. Beck's words "perhaps doesn't even compile at first" cover the first case.1 The page on static and dynamic typing explains the difference. The example files show both kinds of red in each language.

Language Verdict Form
Python stdlib unittest; the first red is a NameError when the test runs
JavaScript stdlib node:test in Node.js; the first red is a ReferenceError when the test runs
TypeScript stdlib the JavaScript runners; tsc reports the missing name before the test runs, but a runner that only removes the types reports a ReferenceError
Java library JUnit; the first red is a compile error, "cannot find symbol"
C idiom a test program with assert; the first red is a compile error
C++ library GoogleTest or Catch2; the first red is a compile error
C# library xUnit.net, NUnit or MSTest; the first red is a compile error
Go stdlib package testing and go test; the first red is a build error, "undefined"
Rust native #[test] and cargo test; the first red is a compile error
Kotlin library kotlin.test on JUnit; the first red is a compile error
PowerShell library Pester
Bash library bats-core, or a script that checks exit statuses
SQL library pgTAP for PostgreSQL; tSQLt for SQL Server
Regex n/a a pattern is tested through the language that uses it
HTML/CSS n/a markup and style rules are tested through a browser

The verdicts follow the test runner, because the cycle needs a fast way to run tests. Python's unittest runs the methods whose names start with test.3 Node.js has the module node:test in its runtime.4 Go's go test runs each function of the form func TestXxx(*testing.T).5 In Rust, a test is a function with the test attribute.6 Java, C# and C++ need a test framework from outside the standard library for the usual workflow. The example files for those languages use a small runner in main, so that they run with the standard library only.

A compile error as red has a cost and a benefit. The cost is that the programmer must write a stub, a function with the right signature and no logic, before the test can fail for the right reason. The benefit is that the type checker joins the tests. A test that calls is_leap("2024") with a string does not compile in Rust or Java, so no test is needed for that case. In Python the same call runs, and only a test finds it.

PythonGitHub
import unittest


def is_leap(year):
    return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)


class LeapYearTest(unittest.TestCase):
    # The tests in the order of the to-do list. Each one added one clause.
    def test_1_year_divisible_by_4_is_leap(self):
        self.assertTrue(is_leap(2024))

    def test_2_other_year_is_common(self):
        self.assertFalse(is_leap(2023))

    def test_3_century_is_common(self):
        self.assertFalse(is_leap(1900))

    def test_4_century_divisible_by_400_is_leap(self):
        self.assertTrue(is_leap(2000))


if __name__ == "__main__":
    unittest.main()
Error output
test_1_year_divisible_by_4_is_leap (test_main.LeapYearTest.test_1_year_divisible_by_4_is_leap) ... ok
test_2_other_year_is_common (test_main.LeapYearTest.test_2_other_year_is_common) ... ok
test_3_century_is_common (test_main.LeapYearTest.test_3_century_is_common) ... ok
test_4_century_divisible_by_400_is_leap (test_main.LeapYearTest.test_4_century_divisible_by_400_is_leap) ... ok

----------------------------------------------------------------------
Ran 4 tests in $TIME

OK
  • Verdict: stdlib. unittest is in the standard library, and python -m unittest finds and runs the test files. The page on unit testing covers the runner.
  • The runner sorts test methods by name. The numbers in the names keep the report in the order in which the cycle wrote the tests.
  • The red step in Python happens at run time. A call to a function that does not exist raises NameError when the test runs, and the runner reports it as an error, not as a failure.

The second cycle, with the fake still in place, is a test that fails on purpose. The runner reports the failure and exits with a nonzero status.

This code fails on purpose. The output below is the error.

import unittest


def is_leap(year):
    return True  # Fake It from the first cycle


class LeapYearTest(unittest.TestCase):
    def test_1_year_divisible_by_4_is_leap(self):
        self.assertTrue(is_leap(2024))

    def test_2_other_year_is_common(self):
        self.assertFalse(is_leap(2023))


if __name__ == "__main__":
    unittest.main()
Error output
test_1_year_divisible_by_4_is_leap (test_main.LeapYearTest.test_1_year_divisible_by_4_is_leap) ... ok
test_2_other_year_is_common (test_main.LeapYearTest.test_2_other_year_is_common) ... FAIL

======================================================================
FAIL: test_2_other_year_is_common (test_main.LeapYearTest.test_2_other_year_is_common)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "$WORK/test_main.py", line 13, in test_2_other_year_is_common
    self.assertFalse(is_leap(2023))
    ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^
AssertionError: True is not false

----------------------------------------------------------------------
Ran 2 tests in $TIME

FAILED (failures=1)
  • unittest tells a failure from an error. A failed assertion is a failure. Any other exception, such as NameError, is an error. Both are red, but a failure is the red that the cycle wants: the test ran and the check was false.
#include <functional>
#include <iostream>
#include <string_view>
#include <utility>
#include <vector>

constexpr bool is_leap(int year) {
    return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}

// The same tests, checked by the compiler.
static_assert(is_leap(2024));
static_assert(!is_leap(2023));
static_assert(!is_leap(1900));
static_assert(is_leap(2000));

int main() {
    // The tests in the order of the to-do list. Each one added one clause.
    std::vector<std::pair<std::string_view, std::function<bool()>>> tests{
        {"2024 is a leap year", [] { return is_leap(2024); }},
        {"2023 is a common year", [] { return !is_leap(2023); }},
        {"1900 is a common year", [] { return !is_leap(1900); }},
        {"2000 is a leap year", [] { return is_leap(2000); }},
    };
    int failed = 0;
    for (const auto& [name, check] : tests) {
        bool ok = check();
        failed += ok ? 0 : 1;
        std::cout << (ok ? "pass  " : "FAIL  ") << name << '\n';
    }
    std::cout << (failed == 0 ? "green" : "red") << '\n';
}
Output
pass  2024 is a leap year
pass  2023 is a common year
pass  1900 is a common year
pass  2000 is a leap year
green
  • Verdict: library. The usual runners, GoogleTest and Catch2, are libraries. This example uses a vector of named checks, so that it runs with the standard library only.
  • A constexpr function can run at compile time. Each static_assert is a test that the compiler runs, and the program does not build if one of them fails.
  • The tests in main repeat the static_assert checks at run time, so that the program prints a report. A function that reads a file or the clock cannot be constexpr, so most tests run at run time.

With static_assert, red in C++ is a compile error for a wrong answer, not only for a missing name. Here the fake from the first cycle meets the second test.

This code does not compile, on purpose.

constexpr bool is_leap(int) {
    return true;  // Fake It from the first cycle
}

static_assert(is_leap(2024));
static_assert(!is_leap(2023));  // the second test: red at compile time

int main() {}
  • The compiler reports that the static assertion failed. In the other languages on this page, a wrong answer is red only when the program runs.
JavaGitHub
import java.util.LinkedHashMap;
import java.util.Map;

public class Main {
    static boolean isLeap(int year) {
        return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
    }

    static void check(boolean condition, String message) {
        if (!condition) {
            throw new AssertionError(message);
        }
    }

    public static void main(String[] args) {
        // The tests in the order of the to-do list. Each one added one clause.
        Map<String, Runnable> tests = new LinkedHashMap<>();
        tests.put("2024 is a leap year", () -> check(isLeap(2024), "2024"));
        tests.put("2023 is a common year", () -> check(!isLeap(2023), "2023"));
        tests.put("1900 is a common year", () -> check(!isLeap(1900), "1900"));
        tests.put("2000 is a leap year", () -> check(isLeap(2000), "2000"));

        int failed = 0;
        for (var test : tests.entrySet()) {
            try {
                test.getValue().run();
                System.out.println("pass  " + test.getKey());
            } catch (AssertionError e) {
                failed++;
                System.out.println("FAIL  " + test.getKey() + ": " + e.getMessage());
            }
        }
        System.out.println(failed == 0 ? "green" : "red");
    }
}
Output
pass  2024 is a leap year
pass  2023 is a common year
pass  1900 is a common year
pass  2000 is a leap year
green
  • Verdict: library. The usual runner is JUnit, which is not part of the JDK. This example uses a small runner in main, so that it runs with the standard library only. The structure is the same: a name and a body for each test, and a report.
  • LinkedHashMap keeps the order of insertion, so the tests run in the order of the to-do list.
  • check throws AssertionError itself. It does not use the assert statement; the next block shows why.

A test with the assert statement can pass with wrong code. The java launcher disables assertions unless it gets the option -ea, so the assert statements below never run.

This code runs but gives a wrong answer on purpose.

public class Main {
    static boolean isLeap(int year) {
        return year % 4 == 0; // bug: 1900 is not a leap year
    }

    public static void main(String[] args) {
        assert isLeap(2024);
        assert !isLeap(2023);
        assert !isLeap(1900); // must fail, but assertions are off
        System.out.println("all tests passed");
    }
}
Output
all tests passed
  • The cycle catches this mistake. The test for 1900 must be red before the fix, and here it is never red. A test that has not failed once has not shown that it runs.
  • JUnit has its own assertion methods, such as assertTrue, which throw whether or not -ea is set.

The first red in Java is a compile error, because isLeap does not exist yet.

This code does not compile, on purpose.

public class Main {
    public static void main(String[] args) {
        // Red: the test comes first, so isLeap does not exist yet.
        if (!isLeap(2024)) {
            throw new AssertionError("2024");
        }
    }
}
  • javac reports "cannot find symbol". To move on, write a stub with the right signature, such as static boolean isLeap(int year) { return false; }. Then the program compiles and the test fails on its check.
#include <assert.h>
#include <stdbool.h>
#include <stdio.h>

static bool is_leap(int year) {
    return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}

/* The tests in the order of the to-do list. Each one added one clause. */
static void test_divisible_by_4_is_leap(void) { assert(is_leap(2024)); }
static void test_other_year_is_common(void) { assert(!is_leap(2023)); }
static void test_century_is_common(void) { assert(!is_leap(1900)); }
static void test_century_divisible_by_400_is_leap(void) { assert(is_leap(2000)); }

int main(void) {
    struct {
        const char *name;
        void (*run)(void);
    } tests[] = {
        {"divisible by 4 is leap", test_divisible_by_4_is_leap},
        {"other year is common", test_other_year_is_common},
        {"century is common", test_century_is_common},
        {"century divisible by 400 is leap", test_century_divisible_by_400_is_leap},
    };
    for (size_t i = 0; i < sizeof tests / sizeof tests[0]; i++) {
        tests[i].run();
        printf("pass  %s\n", tests[i].name);
    }
    puts("green");
    return 0;
}
Output
pass  divisible by 4 is leap
pass  other year is common
pass  century is common
pass  century divisible by 400 is leap
green
  • Verdict: idiom. The C standard library has no test runner. A test program is an array of function pointers and assert, and frameworks such as Unity, CMocka and Check add the rest.
  • A failed assert prints the expression, the file and the line, and then calls abort. The first failure stops the whole program, so the report shows only one red test at a time.

A test with assert can pass with wrong code. When the macro NDEBUG is defined before <assert.h>, assert expands to nothing. Release builds often define it, for example with the flag -DNDEBUG.

This code runs but gives a wrong answer on purpose.

#define NDEBUG
#include <assert.h>
#include <stdbool.h>
#include <stdio.h>

static bool is_leap(int year) {
    return year % 4 == 0; /* bug: 1900 is not a leap year */
}

int main(void) {
    assert(is_leap(2024));
    assert(!is_leap(2023));
    assert(!is_leap(1900)); /* must fail, but NDEBUG removed it */
    puts("all tests passed");
    return 0;
}
Output
all tests passed
  • The cycle catches this mistake. The test for 1900 must be red before the fix, and here it is never red.
  • A test program for C can use its own check macro that does not depend on NDEBUG, or the build can compile the tests without that flag.

The first red in C is a compile error, because is_leap has no declaration.

This code does not compile, on purpose.

#include <stdio.h>

int main(void) {
    /* Red: the test comes first, so is_leap does not exist yet. */
    if (!is_leap(2024)) {
        puts("FAIL 2024");
    }
    return 0;
}
  • C89 accepted a call to an undeclared function and assumed that it returns int. C99 removed that rule, and the compiler used here rejects the call. Even without the declaration, the link step fails, because no definition of is_leap exists.
static bool IsLeap(int year) =>
    year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);

// The tests in the order of the to-do list. Each one added one clause.
(string Name, Func<bool> Check)[] tests =
[
    ("2024 is a leap year", () => IsLeap(2024)),
    ("2023 is a common year", () => !IsLeap(2023)),
    ("1900 is a common year", () => !IsLeap(1900)),
    ("2000 is a leap year", () => IsLeap(2000)),
];

var failed = 0;
foreach (var (name, check) in tests)
{
    var ok = check();
    if (!ok) failed++;
    Console.WriteLine($"{(ok ? "pass" : "FAIL")}  {name}");
}
Console.WriteLine(failed == 0 ? "green" : "red");
Output
pass  2024 is a leap year
pass  2023 is a common year
pass  1900 is a common year
pass  2000 is a leap year
green
  • Verdict: library. The usual runners, xUnit.net, NUnit and MSTest, are packages from NuGet, and dotnet test runs them. This example uses an array of named checks in a top-level program, so that it runs with the standard library only.
  • Each test is a tuple of a name and a Func<bool>. The lambda delays the check until the loop calls it.
  • A test framework adds what this runner lacks: it catches exceptions per test, it reports the values that differed, and it finds tests by attribute, such as [Fact] in xUnit.net.

The first red in C# is a compile error, because IsLeap does not exist yet.

This code does not compile, on purpose.

// Red: the test comes first, so IsLeap does not exist yet.
if (!IsLeap(2024))
{
    throw new Exception("2024");
}
  • The compiler reports error CS0103: the name IsLeap does not exist in the current context. A stub such as static bool IsLeap(int year) => false; lets the program compile, and then the check fails.
JavaScriptGitHub
import { test } from "node:test";
import assert from "node:assert/strict";

function isLeap(year) {
  return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
}

// The tests in the order of the to-do list. Each one added one clause.
test("a year divisible by 4 is a leap year", () => {
  assert.equal(isLeap(2024), true);
});

test("another year is a common year", () => {
  assert.equal(isLeap(2023), false);
});

test("a century is a common year", () => {
  assert.equal(isLeap(1900), false);
});

test("a century divisible by 400 is a leap year", () => {
  assert.equal(isLeap(2000), true);
});
Output
✔ a year divisible by 4 is a leap year ($TIME)
✔ another year is a common year ($TIME)
✔ a century is a common year ($TIME)
✔ a century divisible by 400 is a leap year ($TIME)
ℹ tests 4
ℹ suites 0
ℹ pass 4
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms $TIME
  • Verdict: stdlib. Node.js has the test runner node:test and the module node:assert in its runtime. The ECMAScript standard has no test runner.
  • The runner runs the tests in the order of the calls to test, so the report follows the to-do list.
  • assert.equal from node:assert/strict compares with Object.is. A fake that returns 1 in place of true fails the test.

The first red in JavaScript happens at run time. The module loads, and the call to isLeap throws a ReferenceError because no such name exists.

This code raises ReferenceError, on purpose.

import assert from "node:assert/strict";

// Red: the test comes first, so isLeap does not exist yet.
assert.equal(isLeap(2024), true);
  • No tool stops this program before it runs. A linter can report the undefined name, but the language itself does not. TypeScript reports it at compile time; see the TypeScript example.
TypeScriptGitHub
import { test } from "node:test";
import assert from "node:assert/strict";

function isLeap(year: number): boolean {
  return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
}

// The tests in the order of the to-do list. Each one added one clause.
const cases: ReadonlyArray<readonly [year: number, leap: boolean]> = [
  [2024, true],
  [2023, false],
  [1900, false],
  [2000, true],
];

for (const [year, leap] of cases) {
  test(`${year} is ${leap ? "a leap" : "a common"} year`, () => {
    assert.equal(isLeap(year), leap);
  });
}
Output
✔ 2024 is a leap year ($TIME)
✔ 2023 is a common year ($TIME)
✔ 1900 is a common year ($TIME)
✔ 2000 is a leap year ($TIME)
ℹ tests 4
ℹ suites 0
ℹ pass 4
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms $TIME
  • Verdict: stdlib. TypeScript uses the JavaScript runners. Here node --test runs the file. Node.js removes the type annotations before it runs the code, and it does not check them.
  • The loop registers one test for each row of the table. Each item that the to-do list gains is one more row.
  • The return type boolean is part of the test when tsc checks the code. It rejects a fake that returns 1, because number is not assignable to boolean.

In a project that runs tsc before the tests, the first red in TypeScript is a compile error. The checker reports that it cannot find the name isLeap, and the tests do not run. This page runs TypeScript the way node does, with the types removed and not checked, so the same red shows up at run time as a ReferenceError.

This code raises ReferenceError, on purpose.

import assert from "node:assert/strict";

// Red: the test comes first, so isLeap does not exist yet.
assert.equal(isLeap(2024), true);
  • tsc --noEmit reports this file with error TS2304, Cannot find name 'isLeap'. A setup that only removes types, as Node.js does, skips that check. Run tsc in the cycle to get the red before the code runs.
  • To get to a red that is a test failure, write a stub first: function isLeap(year: number): boolean { return false; }. Then the test compiles and fails on its check.
package leap

// IsLeap reports whether year is a leap year in the Gregorian calendar.
func IsLeap(year int) bool {
	return year%4 == 0 && (year%100 != 0 || year%400 == 0)
}
package leap

import "testing"

func TestIsLeap(t *testing.T) {
	// The tests in the order of the to-do list. Each one added one row.
	cases := []struct {
		name string
		year int
		want bool
	}{
		{"divisible by 4", 2024, true},
		{"not divisible by 4", 2023, false},
		{"century", 1900, false},
		{"century divisible by 400", 2000, true},
	}
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			if got := IsLeap(c.year); got != c.want {
				t.Errorf("IsLeap(%d) = %v, want %v", c.year, got, c.want)
			}
		})
	}
}
Output
=== RUN   TestIsLeap
=== RUN   TestIsLeap/divisible_by_4
=== RUN   TestIsLeap/not_divisible_by_4
=== RUN   TestIsLeap/century
=== RUN   TestIsLeap/century_divisible_by_400
--- PASS: TestIsLeap ($TIME)
    --- PASS: TestIsLeap/divisible_by_4 ($TIME)
    --- PASS: TestIsLeap/not_divisible_by_4 ($TIME)
    --- PASS: TestIsLeap/century ($TIME)
    --- PASS: TestIsLeap/century_divisible_by_400 ($TIME)
PASS
ok  	example	$TIME
  • Verdict: stdlib. The package testing and the command go test are part of the Go distribution. go test builds the files that end in _test.go together with the package and runs each TestXxx function.
  • The table of cases is the to-do list in code. Each cycle adds one row, sees it fail, and then changes IsLeap.
  • t.Errorf marks the subtest as failed and goes on, so one run reports every row that fails. t.Fatalf stops the subtest at the first failure.

The first red in Go is a build error. The test cannot compile, because IsLeap does not exist yet.

This code does not compile, on purpose.

package main

import "fmt"

func main() {
	// Red: the test comes first, so isLeap does not exist yet.
	if !isLeap(2024) {
		fmt.Println("FAIL 2024")
	}
}
  • The compiler reports undefined: isLeap. In a test file, go test reports the same error and prints FAIL with the reason "build failed".
  • Go also rejects an unused variable or import. A test written ahead of the code can stop at such an error first, so read the message before you treat the red as the expected one.
RustGitHub
pub fn is_leap(year: u32) -> bool {
    year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)
}

#[cfg(test)]
mod tests {
    use super::*;

    // The tests in the order of the to-do list. Each one added one clause.
    #[test]
    fn t1_divisible_by_4_is_leap() {
        assert!(is_leap(2024));
    }

    #[test]
    fn t2_other_year_is_common() {
        assert!(!is_leap(2023));
    }

    #[test]
    fn t3_century_is_common() {
        assert!(!is_leap(1900));
    }

    #[test]
    fn t4_century_divisible_by_400_is_leap() {
        assert!(is_leap(2000));
    }
}
Output

running 4 tests
test tests::t1_divisible_by_4_is_leap ... ok
test tests::t2_other_year_is_common ... ok
test tests::t3_century_is_common ... ok
test tests::t4_century_divisible_by_400_is_leap ... ok

test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in $TIME
  • Verdict: native. The #[test] attribute is part of the language, and cargo test builds and runs the harness. The page on unit testing covers the harness.
  • The harness sorts the tests by name, and the numbers in the names keep the order of the to-do list. With several threads, the lines of the report can come in another order.
  • The type u32 rules out negative years at compile time. A test for is_leap(-4) does not compile, so the to-do list needs no item for it.

The first red in Rust is a compile error. A stub moves the red to run time: the macro todo!() has every type, so the function compiles, and it panics when a test calls it.

This code does not compile, on purpose.

fn main() {
    // Red: the test comes first, so is_leap does not exist yet.
    assert!(is_leap(2024));
}

This code panics, on purpose.

fn is_leap(_year: u32) -> bool {
    todo!("the leap year rule")
}

fn main() {
    // The stub compiles, and the test fails when it runs.
    assert!(is_leap(2024));
}
  • The compiler reports error E0425: cannot find function is_leap in this scope.
  • todo!() panics with the message "not yet implemented", followed by the text in the call. The panic is a red that the test runner can report, unlike the compile error.

Behaviour-driven development

Dan North describes behaviour-driven development (BDD) in an article first published in Better Software magazine in March 2006.7 It started as a way to teach TDD. North writes that programmers asked where to start, what to test, what to call their tests and why a test fails. He found that the word "test" was the cause of much of the confusion.7

His first steps changed the names. A tool called agiledox, by his colleague Chris Stevenson, printed JUnit method names as sentences. North then adopted the convention of test method names that start with the word "should".7 At the end of 2003 he began JBehave, a replacement for JUnit with the word "test" taken out.7 Toward the end of 2004, he and the business analyst Chris Matts decided to apply the same vocabulary to requirements. Their goal was one vocabulary for analysts, testers, developers and the business. They started from a story template already in use at their company, "As a [X], I want [Y], so that [Z]", and they wrote the acceptance criteria of each story as scenarios with the form Given, When, Then.7

The Gherkin language of Cucumber writes such scenarios as plain text. A Given step describes the initial context, a When step describes an event or an action, and a Then step describes an expected outcome.8 The text after each keyword is matched to a step definition, which is code.8 The program below is a small step runner. A decorator, which is a higher-order function, registers each step definition with a regular expression.

import re

SCENARIOS = """\
Scenario: a century year that 400 does not divide
  Given the year 1900
  When I ask if it is a leap year
  Then the answer is no
Scenario: a century year that 400 divides
  Given the year 2000
  When I ask if it is a leap year
  Then the answer is yes
"""


def is_leap(year):
    return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)


STEPS = []


def step(pattern):
    def register(function):
        STEPS.append((re.compile(pattern), function))
        return function
    return register


@step(r"the year (\d+)")
def given_year(context, year):
    context["year"] = int(year)


@step(r"I ask if it is a leap year")
def when_ask(context):
    context["answer"] = is_leap(context["year"])


@step(r"the answer is (yes|no)")
def then_answer(context, word):
    assert context["answer"] == (word == "yes")


for line in SCENARIOS.splitlines():
    keyword, _, text = line.strip().partition(" ")
    if keyword == "Scenario:":
        context = {}
        print(line)
        continue
    for pattern, function in STEPS:
        match = pattern.fullmatch(text)
        if match:
            function(context, *match.groups())
            print(f"  ok  {keyword} {text}")
            break
    else:
        print(f"  no step definition for: {text}")
Output
Scenario: a century year that 400 does not divide
  ok  Given the year 1900
  ok  When I ask if it is a leap year
  ok  Then the answer is no
Scenario: a century year that 400 divides
  ok  Given the year 2000
  ok  When I ask if it is a leap year
  ok  Then the answer is yes

BDD keeps the cycle of TDD. It changes the words of the first test, and it can change who writes it. Because the scenario is in the words of the business, an analyst can write it, and the programmer writes the step definitions and then the code.

  • Test-last development. The programmer writes the code first and the tests after, in small steps. Studies of TDD often compare it with incremental test-last development. Fucci and others found that the order of test and code had no important influence, while the size and evenness of the steps did (see Cost).11
  • Property-based tests. TDD drives the code with examples. A property-based test states a rule for all inputs. The leap-year rule from RFC 3339 is such a rule, and a property can check it on thousands of years.
  • Mutation analysis. TDD makes tests that fail before the code exists. Mutation analysis checks if the tests still fail when the finished code changes.
  • Test doubles. A test of code that talks to a database or a clock needs a stand-in, so that the cycle stays fast.

Pitfalls

A test that never failed

The first rule of TDD says to write code only when a test fails, so each test is seen red before it is seen green. A test that never failed may not run. unittest runs only the methods whose names start with test.3 The method below is named check_1900, so the runner skips it, and the suite passes with a bug in the code.

This code runs but gives a wrong answer on purpose.

import io
import unittest


def is_leap(year):
    return year % 4 == 0  # bug: 1900 is not a leap year


class LeapTest(unittest.TestCase):
    def test_2024(self):
        self.assertTrue(is_leap(2024))

    def test_2023(self):
        self.assertFalse(is_leap(2023))

    def check_1900(self):  # not a test: the name does not start with "test"
        self.assertFalse(is_leap(1900))


suite = unittest.defaultTestLoader.loadTestsFromTestCase(LeapTest)
result = unittest.TextTestRunner(stream=io.StringIO()).run(suite)
print("tests run:", result.testsRun)
print("all passed:", result.wasSuccessful())
Output
tests run: 2
all passed: True

In the cycle, this test would have stayed green before the fix for 1900, and the green would have been a warning. Go has the same rule for names: go test runs TestXxx only when Xxx does not start with a lowercase letter.5

Expected values copied from the code

A test must know the answer from a source other than the code. The test below computes the expected value with the same formula as the code, so the code and the test agree on the bug.

This code runs but gives a wrong answer on purpose.

def is_leap(year):
    return year % 4 == 0  # bug: 1900 is not a leap year


def test_matches_rule():
    for year in [1900, 2000, 2023, 2024]:
        assert is_leap(year) == (year % 4 == 0)  # repeats the code


test_matches_rule()
print("test passed")
print("is_leap(1900) =", is_leap(1900))
Output
test passed
is_leap(1900) = True

The fix is a literal answer from the specification: RFC 3339 says that 1900 is not a leap year.2 In TDD the test exists before the code, so the expected value cannot come from the code. That is one of the reasons for the order.

A fake that stays

Fake It is a step, not a result. Beck's fake equals returns true, and he writes that the constant is really "5 == 5", which is really "amount == 5", which is really "amount == dollar.amount".1 The duplication between the constant in the code and the value in the test is what the refactor step removes. If the cycle stops at green, the fake stays. A constant passes any single example, so a list with one example cannot catch it. Triangulation adds the second example for that reason.

Tests that fix the design

A test that checks how the code works, not what it returns, breaks when the code is refactored. Then the third step of the cycle turns tests red without a bug, and the tests stop being a safety net. Mocks that check each call to a collaborator tie the test to the code in this way. The page on test doubles shows the problem and the cost of over-mocking.

Reading the studies as proof

The evidence on TDD is mixed, and the results depend on the setting (see Cost). A claim that TDD halves the defects or slows every team is stronger than the studies support.

Cost

The cost of TDD is the time to write and maintain the tests, and the discipline of small steps. Beck's preface states the hope that TDD can reduce the defect density of code a great deal. It also lists a demand on design: many highly cohesive, loosely coupled components, so that testing stays cheap.1 Several studies have tried to measure the effect on defects and on productivity, with mixed results.

Case studies in industry. Nagappan, Maximilien, Bhat and Williams studied three development teams at Microsoft and one at IBM that adopted TDD. The pre-release defect density of the four products fell by 40% to 90% compared with similar projects that did not use TDD. The teams estimated, as a subjective judgement, that initial development took 15% to 35% more time.9 The limits are in the design of the study. A case study does not assign teams to TDD at random. The comparison projects were similar, not the same, and the time cost is an estimate, not a measurement.

A meta-analysis. Tosun and others summarize the meta-analysis of Rafique and Mišić from 2013, which covered 27 empirical studies. External quality improved with TDD in industrial studies, but it was not significantly different in experiments with students. Productivity improved in academic experiments and fell in industrial ones. Both the gain in quality and the loss of productivity were larger in industrial studies.10

An experiment with professionals. Tosun and others ran an experiment with 24 professionals at three sites of one company. Each person used TDD and incremental test-last development. The study found no statistical difference in external quality. The subjects were more productive with TDD on a less complex task, but productivity fell significantly with TDD on a complex task in existing code. The authors conclude that the choice of tasks can dominate the results of TDD studies.10

A study of the process. Fucci and others analysed 82 data points from 39 professionals. They measured four properties of the process: the order of test and code, the size of the steps, how even the steps were, and the effort spent on refactoring. Small, even steps went with better quality and productivity. The order, test first or test last, had no important influence. Refactoring effort went with worse results on both measures. The authors suggest that the link with lower quality may come from refactoring mixed with other changes. They suggest that the benefits of TDD may come from fine-grained steady steps, not from writing the test first.11

The studies have limits that the authors name. Few experiments use professionals in industry; Tosun and others found only three in the reviews that they checked.10 The reviews use inconsistent terms and a loose definition of an experiment, so they count the studies in different ways.10 Many studies ignore the process itself, such as the size of the steps, and measure only the label TDD.11 The baseline matters as well. The experiments of Tosun and Fucci compare TDD with incremental test-last development, which also writes tests in small steps, so they measure the effect of the order and not the effect of testing.1011 So the studies support a modest claim. Short cycles with tests help in some settings, and the size of the effect depends on the task and the people.

History

  • 2002. Kent Beck published Test-Driven Development, By Example. The preface states the two rules and the cycle red, green, refactor, and part III of the book collects the patterns, among them Fake It, Triangulation and Obvious Implementation.1
  • 2003. At the end of the year, Dan North began JBehave, a replacement for JUnit built around the word behaviour.7
  • 2004. Toward the end of the year, North and Chris Matts decided to apply the behaviour vocabulary to requirements, and they wrote acceptance criteria as scenarios with Given, When, Then.7
  • 2006. North published Introducing BDD in Better Software magazine in March.7
  • 2008. Nagappan and others published case studies of TDD in four industrial teams at Microsoft and IBM.9
  • 2013. Rafique and Mišić published a meta-analysis of 27 studies of TDD, as summarized by Tosun and others.10
  • 2017. Tosun and others published an experiment with 24 professionals, and Fucci and others published a study of the TDD process with 39 professionals.1011

References

  1. Kent Beck, Test-Driven Development, By Example, Addison-Wesley, 2002, Preface (the two rules; red, green, refactor; clean code that works); Chapter 3, Equality for All, pages 15 to 18 (the to-do list, the fake implementation, Triangulation); Index, green bar patterns (Fake It, pages 151 to 153; Triangulation, pages 153 to 154; Obvious Implementation, pages 154 to 155; One to Many, pages 155 to 156)
  2. G. Klyne and C. Newman, RFC 3339, Date and Time on the Internet, Timestamps, July 2002, Section 2, Definitions (leap year); Appendix C, Leap Years
  3. The Python Standard Library, unittest, Unit testing framework, Basic example (methods whose names start with test)
  4. Node.js documentation, Test runner (node:test), introduction
  5. Go standard library, package testing, package overview (func TestXxx and the go test command)
  6. The Rust Programming Language, 11.1 How to Write Tests, Structuring Test Functions (the test attribute)
  7. Dan North, Introducing BDD, first published in Better Software magazine, March 2006, Test method names should be sentences; JBehave emphasizes behaviour over testing; Requirements are behaviour, too; BDD provides a ubiquitous language for analysis; Acceptance criteria should be executable
  8. Cucumber, Gherkin Reference, Keywords; Steps (Given, When, Then); the step definition
  9. Nachiappan Nagappan, E. Michael Maximilien, Thirumalesh Bhat and Laurie Williams, Realizing quality improvement through test driven development, results and experiences of four industrial teams, Empirical Software Engineering 13(3), 2008, pages 289 to 302, Abstract
  10. Ayse Tosun, Oscar Dieste, Davide Fucci and others, An industry experiment on the effects of test-driven development on external quality and productivity, Empirical Software Engineering 22(6), 2017, pages 2763 to 2805, Abstract; Section 2, Related Work (the meta-analysis of Rafique and Mišić, 2013)
  11. Davide Fucci, Hakan Erdogmus, Burak Turhan, Markku Oivo and Natalia Juristo, A Dissection of the Test-Driven Development Process, Does It Really Matter to Test-First or to Test-Last?, IEEE Transactions on Software Engineering 43(7), 2017, pages 597 to 614, Abstract (arXiv version 1611.05994)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/KYEQF7/text.yaml