Understanding the workflow
TDD is a workflow in which we write the tests before we write the production code. It’s often discussed as “red, green, refactor” which are the three primary parts of the flow.
START
Identify the smallest piece of functionality that we want to write. Typically this will be a single path through a single method. It might be a “happy path” where the code does as expected or it could be an error condition. It’s one specific path, though, not a collection of behaviours.
RED - Write a failing test
Write an automated test that fails when you run it.
In order to even get the code to be executable at all, you’ll need to write a tiny bit of the production code. Write only the bare minimum that allows the code to execute without having it actually perform any logic.
Run the test and watch it fail. Sometimes you’ll run the test and it won’t fail and this indicates that there’s a problem somewhere. Most often the test is wrong but sometimes the production code isn’t doing what we expect.
Ensure that the code is failing for the right reasons. If we expect it to return a 0 and instead it throws an exception, that is certainly a failure but it’s failing for the wrong reasons. Go and fix it so it’s failing for the right reason.
GREEN - Make it pass
Now change the production code to make the pass. Do this in the simplest way you can possibly think to do it.
All too often, we try to make the code perfect in this step and that’s wrong. The goal here is just to make the test pass, in the easiest way possible. We don’t care how pretty or how fast the code is, if it doesn’t work. Make it work before doing anything else.
Run the test to verify that it really is working. Run all the tests, if you can, to ensure you didn’t break anything else as you were making this one work.
REFACTOR - Make it beautiful
Now that we have working code, let’s make it beautiful. Refactor it to keep the code clean. Remove duplication. Make the code easy to read. Make it something you can be proud of.
Now run all the tests again to ensure that nothing got broken as we were cleaning the code. If something did get broken then fix it now, before we move on.
CHECK IT IN!
Yes, really check it in to version control. You now have a tiny sliver of production code that is working and tested. By definition, we wouldn’t be at this point if anything were broken. Check it in.
A surpising number of developers are really uncomfortable with checking in this frequently. Get over it. The more often we integrate with the rest of the code, the easier it will be. If you’re not checking in several times an hour then either you’re very new to the technique or you’re doing something wrong.
START AGAIN
Start all over at the top. Find the next tiny slice of functionality and work through the cycle again.