Freitag, 13. Juni 2014

Mock Framework vs Anonymous Class for Unit Tests

I recently
discussed at work what to use for unit tests: a mock framework (e.g. Mockito) or
anonymous classes. Surprisingly for my only one person choose anonymous classes
and there where many votes for the mock framework. I prefer myself the mock framework.

The benefits of a mock framework:

if
you mock an interface within multiple tests with anonymous classes and then you
change the interface you have to touch all of these test files. Even if the new
added method doesn't break the old tests.

if
the interface has many methods but you need only a few of them, the anonymous
class still have to implement each method. So it's quite messy and doesn't
help to read the code.

sure
your IDE will generate the anonymous class with all methods with one keystroke.
But if you want to make explicit which method is used in the test than you have
to rewrite all unnecessary methods to something like this: throw new
RuntimeException("not implemented"). Because otherwise you can't
decide if the test relies on the method to return null or it's not used for the
test.

the
code navigation in the IDE (at least IntelliJ) gets messed up because of the anonymous
test classes. If you want to jump to the method implementation of an interface
and there is one class implementing the interface than IntelliJ will jump
directly to the correct code (ctrl+shift+b). But if in the test classes the
anonymous mock classes are defined than IntelliJ will show you all anonymous
classes which are in this case completely uninteresting.

mocks
are cleaner to write. if you want different return values by different
parameters than you just define them in two lines. In an anonymous class you
have to use if/else.

mocks
are more powerful. You can verify if the methods got called with the right
parameters and are called exactly x times.

There is
just one downside of mock frameworks: you have to learn one of them.

It pays off
to learn a mock framework and to use it because of all the benefits you get
from it (see above). I am currently using Mockito which has a very easy and clean API.