The expectation of mocks

Mocks in unit testing are quite popular in at least some circles. Mocks are surely a powerful tool for unit testing, and they really enable having a great unit testing code coverage, but there’s a catch or a few with using them.

Mocks may introduce a burden of maintenance if the mocks have bad expectations to focus on the the code (coverage) rather than the behavior of the tested unit. Making mocks that behave or expect non-realistically is easy.

So what is the problem with suboptimal mocks? More maintenance than expected. It may mean that one has to re-write (all) the unit tests after fixing a bug or refactoring the code that is tested – even if the behavior wouldn’t change. Why? Because the expectations, the return value, or the side-effect in the mocks were expecting the exact, original, implementation of the unit (and not the behavior) and you fixed or optimized it.

There are times when to use mocks, but it’s easy to use them too much.