DEV Community

Bohdan Pohorilets
Bohdan Pohorilets

Posted on • Originally published at bpohoriletz.github.io on

[EN] To mock, or not to mock, that is the question

  • Time: 5-10 min
  • Level: Beginner/Intermediate

The following checklist is aimed to help you protect yourself from improper usage of mocks and stubs.You may find yourself willing to add/remove items from the list – that is totally OK, just make sure that you stickto your final version.

Mocking has been a controversial practice from the very moment I’ve heard about it for the first time, however mostpeople agree that mocking is a tool and as any other tool it can’t be good or bad, rather it’s developers obligationto pick the right tool for the job and make most of the features it provides.

You’re doing it wrong if:

  1. Mocking things you don’t own – External Service, IO, System, etc.
    • if appropriate, add an Adapter as a wrapper around a thing and mock it instead
  2. Mocking thing under test
    • you may want to introduce and mock collaborator instead
  3. Mocking trivial things
    • you may use an actual thing instead of a mock
  4. Mocking when you should be stubbing
    • test for observable behavior instead of methods being called, methods are only an implementation detail
  5. Mocking only a part of a collaborator’s interface
    • mock it entirely or do not mock at all
  6. Mocking at wrong level/layer
    • for unit tests – mock your nearest neighbor
    • for regression safety – mock dependency at the lowest possible level

If you have not violated any of the upper items, and your tests still are brittle or make you cry at night – that may be an indication of a bad design. If that’s the case – it doesn’t matter either you mock or not because the problem exists between the chair and computer.

References

Top comments (0)