Tuesday, February 1, 2011

Test all your states

I never even thought I would write a post about unit tests.

Why? Because it is such a dogmatic approach, invented by people far from practical experience. The dogmatic application of Test Driven Development would for sure have ruined my company and any single project that I worked on.

That was the disclaimer :)

But...

when you have a library that is actually easy to test because it has a relatively small and well defined interface, it might be a good idea to add unit tests. Even when you are in a hurry and just hack that shit away, a test driven approach might be useful (just notice my use of the word "might").

If you actually do so I'd advice to write tests for every state (do not care for 100% code coverage - it does not say anything and might even be misleading) that comes to your mind even if you think it is ridiculous. I know, depending on the input, this might be impractical, but you can at least try.

Let me give you an example from my current open source project the "Java Minimal Template Engine".

I remember I was thinking about an else inside a foreach while I already had a test for an if without the else part inside a foreach. Obviously two different states. First: simple if inside foreach, second if with else block inside foreach.

I thought, I know the code that evaluates that stuff and I know that it really does not make a difference if the else is inside a foreach or not. And I had a test for that else outside a foreach. And I was right. I skipped the test. Code worked.

Time passed.

I refactored the complete core of the template engine. I felt save to do so as I had a good bunch of unit tests.

After the refactoring, it did make a difference if that else was inside that foreach and - of course - I sill had no test for it. All tests passed after refactoring. But I made a really silly mistake in the refactored code and else inside foreach was broken. And it wasn't me who discovered that ;)

See the point? Just because you know the code and you know it does not make a difference now, does not mean this will remain true when time passes and the code changes. It might not even be you who changes that code.

Those tests are there to protect you, so either take them seriously or skip them completely. So: Test all your states.

No comments: