Test-Driven Development


(Andy Wootton) #21

I’ve started playing the TDD game again in Clojure but I had a bit of a shock. I copied an example out of a book, wrote some code and fixed it so the test passed. I then saw something else I could test, so wrote my own test and that passed too.

A few minutes later I noticed I’d made a typo in the 2nd test. It shouldn’t have been passing. Does this happen often in TDD? Is this a good reason to write the test first, to check it knows how to fail?


(Dave Evans) #22

The procedure I use is to:
Write a single test.
Run it to ensure it fails.
Write the code to make it pass.
Refactor the code so that it makes sense (and still passes).

I sometimes find that I then need to write a second test to check that the ‘failing’ condition also behaves properly. It is possible to write tests that pass even if what I code fails horribly.

I think that TDD is a skill that takes quite a long time to get good at.


(Andy Wootton) #23

I imagine it is. I’d assumed that the tests were so simple they wouldn’t have ‘bugs that fake working’. It seems that if you introduce a test that already passes, you need to make a temporary change that show the test works or you might get the nightmare case of 2 bugs that cancel out, so when you remove one, something miles away crashes… not that it’s ever happened to me, obviously :slight_smile:


(Marc Cooper) #24

The advice from @DaveDev is solid. Making sure your test fails is key.

I’ll quite often write against a passing test – for lots of reasons – but I always ensure I go back and make it fail regardless of how “simple” things appear. It’s shocking how often I catch myself out :roll_eyes:

When pairing during interviews, this is frequently the start of a conversation. It’s surprisingly hard to convince juniors (and not so juniors) to run the failing test – usual reasons. Not all, of course. But it’s a good indicator, ime, of someone who genuinely understands what they are doing rather than just cranking the handle (i.e. believing that writing softare that works is sufficient).