There are three distinct phases to test-first development. We call them red bar, green bar, and refactor, because those are the visual cues you get from your unit testing framework. When all your tests pass, you get the green bar. When you have a test that’s failing, you get the red bar.
When you first write the test there’s no code to test yet. It can’t fail yet—it can’t even compile. If you’re using a modern integrated development environment (IDE), you’ll see feedback that says, “I don’t know what you’re referring to with this production code. You want to add one and one. I’ve never heard of a method called add(). What is that?”
The next thing you do is you “stub out” the production code so that you can compile the test. So you write the method called add() but you stub it out. You’ve taken two numbers as input parameters but you just returned zero because you’re not worried about the implementation yet.
This is a very simple example, and you don’t need to figure out a lot to add two numbers. But imagine it was a double-declining amortization algorithm or something else very complex. First, you want to decide how you’re going to call it. What does it need? What do you expect to get back? But for now you’re just going to return a dummy value. That’s called “stubbing out a method.”
Once you stub out that method, you can compile and run the test. Of course it fails, and it tells you it’s failing by displaying the red bar. Observing the red bar at this point is a test of the test. It tells you the test can fail, and that’s important to prove because a test that can’t fail is worse than no test at all.
Move on to implementing your code by writing the simplest code needed to make the test pass. Once you do that, you should see the green bar—your test passes. The next step is to clean up the code for quality, if necessary, so the code is easier to read and work with in the future. Also clean up your test. Then go back to step one and create something else—another little bit of intention or behavior.
What you’re saying when you write tests is, “Hey code, can you do this?” And of course the code can’t do it, so it fails. It says no and you reply, “Okay, let me show you how.” Then you implement it and say, “Hey code, can you do this now?” And you go back and forth like that.
It’s sort of a dialogue with your code, which is very nice. Do this in the small, over and over, this cycle of red bar/green bar/refactor, red bar/green bar/refactor, over and over and over. Build a whole system that way.
From the outside this may appear a bit tedious, but it’s not. Not at all. It’s a rhythm, like the drumbeat in a song.