Everything You Need to Know About TDD - Part 1
a.k.a. “Mastering TDD” a.k.a. “Advanced TDD”
For the past 9 months, I’ve been focusing on learning test-driven development (TDD). This is easier said than done. While the principles of TDD are easy, fluency (not that I can claim it) is challenging. I continue to meet people who have given up because the learning process has been too hard. I think this is largely due to the lack of intermediate materials.
The goal of this article is to try to collect all of the knowledge and resources that I’ve come across to move beyond the basics of TDD and become comfortable practicing it.
The Basics
The basics for TDD are easy:
- Write a failing test (often called “red”).
- Write the code that makes the test pass (often called “green”).
- Refactor (…called “refactor”).
Here is a slightly more nuanced take:
- Write a test and confirm that it fails for the expected reason.
- Write the minimal production code necessary to make the test past.
- Refactor the production code and the test code.
Q. Why do you make sure the test fails in step 1?
A. We don’t have tests for our tests. By ensuring the test fails, we make sure that the test is going to successfully catch a problem in our code, if our code was to break in the future. Countless times I’ve made a mistake in my test boilerplate meaning that my tests passed even when they shouldn’t have. This is a crucial step!
Q. For step 2, can I write more than the minimum production code necessary? This seems like it could get annoying.
A. This is highly recommended and, once you get used to it, from my experience it got less annoying. One reason why this is recommended is that it ensures you always have complete test coverage of the code you are building.
Q. Why refactor the test code as well in step 3?
A. What we’re aiming to do in TDD is to test the public API of our code (more on this later). Our tests are the first clients of our public API. We want them to be readable, since they will demonstrate how to utilize our code. We also need our tests to run quickly so we run them regularly. If we have sloppy test setup, this may harm our test runtime, once our system gets large.
Have a Question, a Different Opinion, or Spot a Mistake?
Please send me a tweet: @willspringersec
Further Resources