Testing is a vital part of modern development. Code without tests isn’t code – it’s random scribblings that may or may not be executable. Even if they are executable, the only way you can tell if they all work is by loading your application or website, and trying out every single thing that a user could possibly do.
Test-driven development (TDD) is a really nice way of developing software by writing tests before you write the code. If you’re not used to this way of working then it sounds like a weird way to do things, but hear me out.
Imagine you’re building a web app. You wouldn’t just write the whole thing, then open up a browser and see if it works. You’d write a small bit, open the browser and see if it does the expected thing. If it didn’t, then you’d work out why, then fix it, and look again. Then you’d do the next bit.
TDD is just like that, but easier. With TDD, instead of going to the browser each time and seeing if what you’ve just written works, you write a bit of test code that checks that your code does the expected thing. Once it does, you write another test that checks the next thing you’d like it to do. The advantage of working this way is that every time you run your tests, you’re running all of the previous tests you’ve written. That way you can see if something you’ve written to get the most recent thing working ended up breaking something you did earlier. If you were going to do this the old way, you’d either have to check everything every time you made a change, or risk breaking other things that you’re not concentrating on right now. A good test suite will run in under a second, so you get instant feedback whenever you make a change.
Using TDD also means that you end up thinking about the application in a much more sensible way. It forces you to limit the interactions between different bits of the code, which makes the code much easier to modify at a later date.
A side-effect of TDD is that you end up with a comprehensive test suite that can be used to verify the behaviour of your app.
Ok – I’m sold!
Now, TDD takes some practice. You need to learn the tools and the techniques so you can get to the point where you actually write code faster when you’re test-driving it. So, how do you get there?
If you’re not sure whether you want to get the book yet, have a look at the author’s introductory testing article on Script Junkie.