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.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: