Services

Resources

Company

TDD (test-driven development)

Test-driven development (TDD) is a way of writing code in small cycles where the test comes first. You write a test for the next bit of behaviour, watch it fail, write the simplest code that makes it pass, and then clean up the code while the tests stay green. The cycle is often called red, green, refactor.

How it works

Red: write one test that describes what the code should do and run it, so you see it fail for the right reason. Green: write the least code that makes it pass, even if it is crude. Refactor: remove duplication and improve names with the test as a safety net. Then repeat with the next case, usually a few minutes per cycle.

For example, the first story in the One2N Go bootcamp's number filtering exercise asks for the even numbers in 1 to 10. A table-driven test expects evenNumbers([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}) to return [2 4 6 8 10]. With a stub that returns nil, go test fails with got [] want [2 4 6 8 10]. A loop that keeps n%2 == 0 turns it green. When the odd numbers story arrives, you refactor both into one filter(nums, cond) function and the old tests confirm nothing broke.

Why it matters in production

TDD leaves behind a test suite that runs on every change in CI/CD, and it pushes code toward small functions with clear inputs and outputs. It is harder where code has side effects, such as time, randomness or the network: pass those in as interfaces or functions so a test can supply a fixed clock or a fixed dice roll. Tests written first still miss concurrency bugs, so run them with go test -race to catch a race condition.

See also

On the One2N blog

References

  1. Test driven development (Martin Fowler)

  2. Table driven tests (Go wiki)

Four-panel comic about test-driven development: Asha must filter even numbers and writes the test before the code; the red, green, refactor cycle; a table-driven test expects evenNumbers of 1 to 10 to return 2 4 6 8 10, fails on a stub, then passes; Asha refactors even and odd into one filter function with the tests still green.