The importance of Unit Tests (even for small items)

Recently bought a book, and just started browsing through it. The book is Java Puzzlers by Joshua Bloch and Neal Gafter.

Read the first puzzle, and realized the importance of unit tests, even for seemingly trivial methods.

The first example is a method like this:

public boolean isOdd(int number) {
    return (number % 2 == 1);
}

Now, at first glance, it looks good, but if you were to write a unittest for it like this (normally, I’d have a method for each different test case, but for this purpose, it’s not required):

public void testIsOdd() {
    assertTrue(fixture.isOdd(5));
    assertTrue(fixture.isOdd(-5));
    assertFalse(fixture.isOdd(6));
    assertFalse(fixture.isOdd(-6));
}

would you expect it to pass?

Of course not. Otherwise, why would I be asking the question.

If you remember that the % operator return value is the same sign as the the value being checked, you’ll realize that -5 will break the test.

So, let’s take this a step further. Suppose you fix your code as such:

public boolean isOdd(int number) {
    return (!number % 2 == 0);
}

So now it’s correct and the tests pass. What if another developer comes along and sees the ! and decides they don’t like negative ifs and changes the code to the original code? If they weren’t aware of the actions of % (and I probably wouldn’t have thought about it), then without the unit tests, the broken code could get checked in.

Now obviously this is a contrived example, but it shows how something even this simple can be protected by unittests.

It's only fair to share...
Share on FacebookGoogle+Tweet about this on TwitterShare on LinkedIn

Leave a Reply