Skip to content

Test Driven Development (TDD) fundamentals

BraveJero edited this page Oct 4, 2021 · 5 revisions

"In TDD, the tests are written from the perspective of a class's public interface. They focus on the class's behavior, not its implementation. Programmers write each test before the corresponding production code. This focuses their attention on creating interfaces that are easy to use rather than easy to implement, which improves the design of the interface." — The Art of Agile Development by James Shore and Shane Warden

Four steps of TDD

In simple terms, in TDD you write your unit test first, watch it fail, and then implement code changes until the test passes.

tdd

Step 1: Feature request

This is the hardest part of the TDD cycle because the concept of tests driving your code seems backwards.

Imagine what behavior you want your code to have, then think of a small increment. Next, think of a test that will fail unless that behavior is present.

Step 2: Write a test

Now write the test. Write only enough code for the current increment of behavior. If it takes more, just try for a smaller increment next time.

Step 3: Write code

The saying is, "Don't write any production code unless you have a failing test."

So, write just enough production code to get the test to pass. Don't worry about writing clean code, just do what you need to do to make the test pass.

Step 4: Refactor

For each problem you see, refactor the code to fix it. Work in a series of very small refactorings and run the tests after each one.

Step 5: Iterate

Each time you finish the TDD cycle, you add a tiny bit of well-tested, clean code.

The key to success with TDD is small increments.

References

Clone this wiki locally