Improving your reds is a simple tip that is described by Steve Freeman and Nat Pryce in their wonderful book Growing Object-Oriented Software, Guided by Tests.
It consists in a small variation to the TDD cycle in which you watch the error message of your failing test and ask yourself if the information it gives you would make it easier to diagnose the origin of the problem in case this error appears as a regression in the future. If the answer is no, you improve the error message before going on to make the test pass.
Investing time in improving your reds will prove very useful for your colleagues and yourself because the clearer the error message, the better the context to fix the regression error effectively. Most of the times, applying this small variation to the TDD cycle only requires a small effort.
As a simple example, have a look at the following assertion and how it fails
assertThat(new Fraction(1,2).add(1), is(new Fraction(3,2)));
java.lang.AssertionError:
Expected: is <Fraction@2d8e8c3a>
but: was <Fraction@2d8e84b8>
Why is it failing? Will this error message help us know what's happening if we see it in the future?
The answer is clearly no, but with little effort, we can add a bit of code to make the error message clearer (implementing the toString()
method).
@Override
public String toString() {
return "Fraction{" +
"numerator=" + numerator +
", denominator=" + denominator +
'}';
}
java.lang.AssertionError:
Expected: is <Fraction{numerator=3, denominator=2}>
but: was <Fraction{numerator=1, denominator=2}>
This error message is much clearer that the previous one and will help us to be more effective both while test-driving the code and if/when a regression error happens in the future, and we got this just by adding an implementation of toString()
generated by our IDE.
Take that low hanging fruit. Start improving your reds!
Top comments (2)
The same is true for JavaScript. Jest (jestjs.io/) is especially powerful in that regard by allowing you to create your own matchers and/or overwrite existing ones and their messages while already delivering useful formatting on the existing ones (for example,
expect(array).toHaveLength(3)
will output the whole formatted array with the error for easy inspection.That's a nice example as well!