July 3, 2012

Mockito: Default values and how to get more out of them

The problem

A while ago I had an interesting discussion with two of my colleagues, Dan Bergh Johnsson and Daniel Deogun, about how to change the default return value of unstubbed methods in Mockito. The background for the discussion was that by default, Mockito returns default values for unstubbed methods and these default values are usually good enough. In some cases that default value will be null and if the code being tested tries to use the returned null value it will cause a nullpointer exception. The stack trace of that exception will quite easily give away that the cause was an unstubbed method.

However, if the tested code calls an unstubbed method and, instead of using the null value directly, stores it and uses it later. Then the stack trace of the nullpointer exception will no longer reveal that the cause was an unstubbed method but will point to some random code line that can be far away from where the unstubbed call actually took place. When this happens it usually takes some time to figure out what the root cause was. Lets take a look at how we would approach this situation and how we can get a more informative error when it occurs.