Monthly Archives: July 2014

Prefer logging to comments in tests

I see this a lot:

testMyAwesomeCode() {
    //create object
    obj = factory();

    //set things up
    obj.setup();

    //ask for authorisation
    obj.getAuth();
    //....
}

There’s nothing inherently bad with this, it’s just that it could be a lot more useful if instead if were this:

testMyAwesomeCode() {
    log.debug("create object");
    obj = factory();

    log.debug("set things up");
    obj.setup();

    log.debug("ask for authorisation");
    obj.getAuth();
    //....
 }

The logs serve the same purpose as the comments in the original code, and now when one of the tests starts failing the logs are there to help see what’s going on and why.

I find this works better with a logging and testing system that is usually silent (i.e. the above logs aren’t printed) by default and can then be enabled with a run-time option. That way the noise isn’t there when it’s not needed.