Forem

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

Image of Docusign

Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay