Friday, 20 July 2012

Teaching TDD


I've been evangelising TDD at work and have been quite surprised by the how it has been taken up. In general, people are excited to learn about TDD and there was an excellent turnout to talks a colleague and I have given. We ran through the full test driven cycle: 
  1. Write a test
  2. Watch it fail to compile
  3. Fix the compile errors
  4. Run the test and watch it fail
  5. Write just enough code to make the test pass
  6. Watch the test pass
  7. Refactor
  8. Go to step 1
We demonstrated each one of these steps with 3 or 4 unit tests for an example class. However, no matter how much I repeat that you shouldn't write code before a test and that you should only write enough code to make your test pass, people struggle to get their heads around that idea. I still often come across people who are trying to learn TDD, but are not following this pattern.

I was prompted to start running the mini TDD courses when I saw a piece of code a junior member of my team was working on. He was still not used to the idea of writing tests first, so I sat with him and helped him write a bit of code in the TDD style. While he coded in front of me, I was able to point out when he'd skipped too far ahead and had written code that he didn't have a test for yet and it was only after a few round of this that he finally got what TDD was all about. 

I think that a practical one-on-one session like this is the only way to really show someone how to do TDD. Sit with them and have them start writing code and just gently nudge them when they've skipped a step. I've done this a couple of times now and it only takes a couple of tests before it sinks in.

No comments: