Kaushik's Blog

Thoughts on Testing

Today, I spent some time reading about unit testing, as is my wont. Via Hacker News, I came across the Google Testing Blog, which has some really interesting ideas. Here are a few:

Reduce nesting and indentation levels by using guard clauses to return early or raise exceptions from functions when certain criteria are not met. This helps eliminate blocks of code that look like

if condition1:
    if condition2:
        if condition3:
            doThing()
        else:
            raise RuntimeError("Condition3 failed!")
else:
    logger.warn("Condition 2 failed; could not do thing.")

The second if in this chain fails silently. In fact, this example is very similar to a bug I identified and fixed last week.

The advice to not overuse mocks is thought-provoking.

I especially liked this piece of advice:

Leave the campground cleaner than you found it