Skip to main content

Essential Test-Driven Development

programming
tdd
refactoring
Author

Rob Myers

Published

Feb 5, 2026

TDD = test-first + refactoring (original XP practices).

A good engineering specification is clear, readable, and easily understood by both current and future developers.

Essentialism: Necessary, nothing extra. “Less, but better” –Dieter Rams

Emergence: “… a process whereby larger entities, patterns, and regularities arise through interactions among smaller or simpler entities that themselves do not exhibit such properties.” – Wikipedia

People naturally talk about software behaviors using examples. By capturing that example in a small bit of automated, executable specification (a test), the team can be sure of the following: - The example doesn’t get lost in translation later. - Once complete, the implementation works correctly. - The behavior captured by that example is never mistakenly broken during the entire life of the product.

Unit of behavior

# example 1
box = Box()
box.add("red pen")
assert box.has("red pen") is True

# example 2
box = Box()
box.add("red pen")
assert box.has("blue pen") is False

Testing behavior usually involves calls to mulitple methods.

Behavioral boundaries

dial = Dial("volume")
indicator = Indicator("volume", listenTo=dial)
dial.setTo(5)
assert indicator.level() == 50

boundaries (-1, 0), (10, 11)? what about (0,1)? example indicator’s light

When TDD is used diligently, every software defect is either a missing test or a vaguely specified test (potential misunderstanding and/or safety net gap).

TDD vs BDD

BDD builds upon TDD, but BDD differs from TDD in the following ways: - The tests are “business-facing” (i.e focus on product specification) while TDD is often a runnable engineering specification. Results from collaboration btw business and engineers. - TDD is included as a practice within the BDD cycle (i.e. it’s not TDD or BDD).

TDD and LLMs

Would you trust vibe coded code for financial, medical, or safety applications?

Computers can’t read our minds, and they don’t do well with ambiguous instructions.

The real power of TDD comes from thinking about what the software needs to do and coming up with examples to represent that behavior.

Basic moves

Test-Driven Development (TDD) is, in many ways, a cooperative game that you play with the computer.

(TDD diagram with more details)

Thinking in tests

Given that the word “test” carries some cultural baggage, you might want to think of each test as being an example, specification, or scenario. Besides, it isn’t really a test until it passes for the first time. From then on, that test checks whether the behavior you’ve developed remains intact indefinitely.

Given/When/Then == Arrange/Act/Assert, but GWT is a clearer language

To write a test, you must know what the outcomes should be. Consider writing “then” part first.

Writing the test guides your design of the object’s interface from the perspective of code that calls your code.

Three Basic Techniques

  1. Fake it till you make it: use the simplest implementation to pass the test (ex hard coded constants)
  2. Triangulation: writing another test related to the same behavior as the previous test.
  3. Obvious implementation: the simplest implementation that is sufficient to pass the failing test without faking anything.

Baby steps: all big software changes are really made up of many very small changes.

Fail cleanly / Fail for the right reason.

Always run all tests, rather than just the new one.

Code smell: A common pattern visible in the structure of your code that indicates the internal design needs to be improved.

A unit test must not have assertions separated by more behavioral code. In other words, a test should not have more than one when step.

Exceptional Behaviours

Throwing/raising an exception/error creates an alternative return path, i.e. a special behavior (indended for developer or devops person). As such it should be tested, along with a meaningful error message.

Sustaining a Test-Driven Practice

A truly test-driven team is more focused on the “what” and less focused on the “how.”

Test code needs to be maintained with at least as much diligence as the implementation code. No amount of automated testing can replace Exploratory testing by a professional tester.

Attributes of good unit tests: - Fast (< 60 sec) - Clear (excruciatingly obvious: code that is so clear that its purpose and behavior are unambiguous) - Concise/Focused (each unit test should be as brief as reasonably possible and should test only 1 behavior) - Independent (each test must be able to run individually and independently of other tests) - Repeatable (a test must give the same result every time it runs regardles of time of the day, previous tests, test environment, etc)

Where to Start We naturally think in examples Just enough upfront design: CRC cards (class/concept, responsibilities, collaborators)

    +--------------------------------+
    |              Class             |
    | Responsibility |  Collaborator |
    +--------------------------------+

CRC cards are neither code nor documentation. Each CRC session should start with a set of fresh blank cards.

Test behavior, not implementation

Test behavior, not data structures (example Battleship game, 10x10 board, test that a newly created board has a width and height of 10 is a data structure test)

Test only what is known. What you test separately, you can change independently. Aka if you have good unit test coverage, you don’t need to debug your code.

Zombies: Zero, One, Many, Boundaries, Interface, Exceptional conditions, Simple (scenarios and solutions, reminder to take baby steps)

At any point the code does (behavior) one of three things: 1. Answers a query by returning a value (easiest to test) 2. Alters the state of an object 3. Delegates to another object or function (hardest to test)

On a good TDD project, the ratio of test code to implementation code is 2-3 more LOC of test code.

Good tests and good code look very different, and their code smells are different too.

Test code smells

  • Unhelpful Test Name (what makes this test unique?)
  • Unhelpful Instance Names (result, actual, expected, want, got are smelly; use domain language)
  • Copy/Paste/Modify (prefer writing tests “from scratch”)
  • Duplicate “Given” (extract to “Before Each”)
  • Excessive “Given” (are you trying do test too much? consider “Builder pattern”)
  • Rejected “Given” (resetting/modifying “Before each”)
  • Forced Return Value (mixing query and command, success/fail status. NB: old tradition of returning “success” in cli commands. Try renaming the test as “do_something_and_return_something_or_return_something_else)
  • Coupled assertions (related behaviors?)
  • Extended narrative (given-when-then-when-then-when-then…, multiple scenarios)
  • Unrelated assertions
  • Unfailing assertion (testing constructor?)
  • Redundant assertion
  • Repeated assertions (almost duplicates)
  • Branching code (if or loop in the test, testing boundaries)
  • Calculations/formula (no formulas in tests, use well known constants; ex. speed of light, water boiling temperature, …)
  • Frequent changes to “Given”

Test Doubles

  • Fake: a substitute dependency that has real (but not production-ready) behavior
  • Stub: a very simple replacement object that returns predefined values
  • Mock: a test double that is generated by a mocking framework, used in a test, and then discarded once the test is done.
  • Spy: a test double that records each method call made to it and parameteres passed to those methods (useful for interaction-based test scenarios)
  • Nullable: is a stub that exists within production code, but is accessed only by tests (A Nullable is a class with the ability to “turn off” its interaction with external systems. – James Shore)

Testing Legacy Code

Legacy code is code you are afraid to change – James Shore

Adding new features to the legacy code requires refactoring which needs a good testing safety net, but untested code usually resists testing. To make it more testable we need to refactor it first. Solution? Characterization testing (capture and preservation of existing behaviors).

Don’t cover all your legacy code with characterization tests at once, cover just the code that is about to change.

Characterization testing recipe:

  1. Ask 3 questions: 1.1 What does this class or method do? Write a brief description in a new to-do file for all behaviors (all code paths, ifs, loops, throws) assuming everything exists for a good reason. 1.2 What is preventing you from easily writing a test for those behaviors? note bad names, absence of meaningful return values, dependencies. 1.3 What can be done about the challenges listed under Question 2? write down any ideas that might make testing easier
  2. Start writing a test: Call a costructor and a method with some test data. Add an assertion.
  3. Run the test and learn from failure.
  4. Update the test with learnings from step 3.
  5. Repeat 3 & 4 until the test passes.
  6. Goto step 2 for the next behavior. Continue until all code paths are covered.

Keep a copy of “Working effectively with legacy code” handy. Make sure your test code does not exercise real production code. Consider disconnecting the network.

Prefer using unit-testing frameworks for writing characterization tests.

Renaming and Extract method, Move method are the most likely refactorings used during characterization testing. If your IDE can perform such refactorings for you, they are likely to be safe.

What would it mean for software to be “antifragile”? If a Black Swan user story is properly implemented, the code will become even more flexible and potentially able to handle future requests more easily. Strengthening effect on the team.