Nov 26 2007
My Great Secret to Writing Unit Tests
Always write the trivial unit test.
A lot of developers fall out of the habit of writing unit tests, and I definitely understand that pain. I can fall out of the habit, too, and there’s something oddly intimidating about looking at a class and creating a unit test for it. It’s not clear to me what the underlying problem really is: perhaps there just too much to test, and so it is hard to know where to start. Whatever the reason, I find that I can break through that boundary if I just create the test and write:
@Test
public void checkFramework() {
assertTrue(true);
}
Once I get past that point, suddenly the unit tests just flow out of me. But if I don’t get past that point, it’s easy to wander off into cowboy land.
Popularity: 9% [?]
It’s something akin to a writer’s block — I have the same thing when I’m supposed to work on any text. Typing down anything, even the most dull, boring and obvious first phrase will usually open the floodgates. Then, like the trivial assertion, the first phrase can be deleted when there’s good text to replace it.
I do the same thing by testing the constructor argument contract for Null values in parameters.
In JUnit/Groovy syntax:
public void test_constructor_arg_contract() {
shouldFail(IllegalArgumentException) {
new MyObject(null)
}
}
From there it is easy to write a 2nd test the verifies the constructor’s success path.
“Hamlet D’Arcy” and “Rytmis”? This blog may not be the most popular, but we’ve definitely got the coolest names for our commentators. :D
@Hamlet
That’s one of my favorites, too. Although you should probably check out NullArgumentException if you’re in the habit of writing stuff like that.
@Rytmis
Writer’s block is a good comparison. Although it’s kinda funny — even though I’ll get hung up on unit tests, I rarely (if ever) have trouble setting in to write a class/module/whatever. The only language I have trouble doing that in is OCaml, and I think that’s because OCaml’s type system punishes you if you start coding before you really grok what it is you’re supposed to be describing.
There seems to be an important difference in writing code and writing tests — I, too, can write code pretty much without hesitating for a second — I’m not saying it’s going to be good code, but the block usually just isn’t there — but tests take some more thinking. Maybe it’s because when you’re writing a test, you’re operating on a different level — the what instead of the how.
For me, coding without the unit tests is kind of like thinking out loud. It’s relatively easy to do, but more often than not, it doesn’t make sense to anyone else. :)