In a public ‘memo to self’ style, I thought to write down some pros and cons of using mock/stub objects in testing:

Pros:

  • You get to test method logic in addition to outcome
  • You can mock away expensive method calls which are not crucial to method being tested (like network requests, disk operations etc)
  • You get complete control to how subcomponents of a test method behave
  • You can test for conditions which are difficult/expensive to do automatically without mocking (eg. pretend disk full situation, network connection breakup, see what happens after 2038-12-31 23:59:59, fake two digests to collide which usually is a 1/10000000000000000000000000000000 chance etc)

Cons:

  • Refactoring may require heavy changes to test methods as well, because with mock objects you often don’t test expected result, but application logic
  • Mocking can become quite tedious (can be alleviated a lot by improving mock frameworks)
  • You risk doing mocking the wrong way and having tests pass while real implementation will fail (alleviated by good integration tests)

On the plus side, I find last entry the most beneficial and as such I’m trying to find out is it worth the trouble to become a pure mockist TDD practitioner.

As of today, Ruby unit testers are happy to have flexmock 0.6.0. The features added seem to make mocking even easier than before, but it doesn’t work with all our test suites yet. Bummer.

Leave a Reply