Tuesday, March 10, 2009

Do your unit tests even get to assertFoo?

Lots of my unit tests involve looking up data in a database. My tests often look something like this:


public void crazyDatabaseTest() {
if (...) {
if (...) {

}
else {
for (SomeThing doodad: things) {
assertFuz(...)
}
}
}
}



Now what happens if things is empty, or if by some chance my conditional logic breaks down and no asserts even get executed? To catch myself from this blunder, I often set a testAnything boolean like so:



public void crazyDatabaseTest() {
boolean testedAnything = false;
if (...) {
if (...) {

}
else {
for (SomeThing doodad: things) {
testedAnything = true;
assertFuz(...)
}
}
}

if (!testedAnything) {
fail("Nothing got tested!");
}
}

No comments:

Post a Comment