Tuesday, May 17, 2011

The why of unit testing

When you sit down to start writing test code, it's sometimes hard to see the wood for the trees. It's hard to make sense of writing a unit test for a piece of code which is maybe 20 lines long, and you can run it as part of the app and see that it works.

So far so good. It works, who needs tests.

Well, what about after someone else changes the code? Will it still work?

What about after someone changes the code in another branch, and a source code control system automagically merges your code. My change in this branch, your change in that branch, and an automated system decides the changes don't conflict, and puts them both in the merged version.

You can of course check each merged file, say all 40 source code files that you changed this week. You might spot the place where our changes don't play nice. But better still, you can run the unit tests. All of them, hundreds of them built up over time.

And that's the reason why you write unit tests, even for code that's obviously right.

Because things change, other people work on the code, some of them are new to the code base, some of them are new to the language.

So only about 5% of the value of units tests are to make sure the code works now, the real value of the unit tests are to make sure the code still works later.

There's other reasons too, but that's another post.

No comments:

Post a Comment