Interview Questions

How simple is 'too simple to break'?

JUnit Questions and Answers


(Continued from previous question...)

How simple is 'too simple to break'?

The general philosophy is this: if it can't break on its own, it's too simple to break.

First example is the getX() method. Suppose the getX() method only answers the value of an instance variable. In that case, getX() cannot break unless either the compiler or the interpreter is also broken. For that reason, don't test getX(); there is no benefit. The same is true of the setX() method, although if your setX() method does any parameter validation or has any side effects, you likely need to test it.

Next example: suppose you have written a method that does nothing but forward parameters into a method called on another object. That method is too simple to break.

    public void myMethod(final int a, final String b) {
        myCollaborator.anotherMethod(a, b);
    }

myMethod cannot possibly break because it does nothing: it forwards its input to another object and that's all.

The only precondition for this method is "myCollaborator != null", but that is generally the responsibility of the constructor, and not of myMethod. If you are concerned, add a test to verify that myCollaborator is always set to something non-null by every constructor.

The only way myMethod could break would be if myCollaborator.anotherMethod() were broken. In that case, test myCollaborator, and not the current class.

It is true that adding tests for even these simple methods guards against the possibility that someone refactors and makes the methods "not-so-simple" anymore. In that case, though, the refactorer needs to be aware that the method is now complex enough to break, and should write tests for it -- and preferably before the refactoring.

Another example: suppose you have a JSP and, like a good programmer, you have removed all business logic from it. All it does is provide a layout for a number of JavaBeans and never does anything that could change the value of any object. That JSP is too simple to break, and since JSPs are notoriously annoying to test, you should strive to make all your JSPs too simple to break.

Here's the way testing goes:

    becomeTimidAndTestEverything
    while writingTheSameThingOverAndOverAgain
        becomeMoreAggressive
        writeFewerTests
        writeTestsForMoreInterestingCases
        if getBurnedByStupidDefect
            feelStupid
            becomeTimidAndTestEverything
        end
    end

The loop, as you can see, never terminates.

(Continued on next question...)

Other Interview Questions