3 ms·
When discussing these in Python, you need to be careful to differentiate between "mocking" and "monkey patching", especially so because both of those are provid
by necovek 5y ago
When discussing these in Python, you need to be careful to differentiate between "mocking" and "monkey patching", especially so because both of those are provided by Python's standard library "mock" module.
Mocking, and specifically mocking with Python mock module, is a quick approach to construct faked objects that simply do not fail and which log any method execution on them. Dependency injection is usually done with more complete fakes, ideally with tested fakes (fakes which pass the same sets of tests as the original, "production" implementation does).
Monkey-patching is what allows Python developers to avoid dependency injection altogether. It has its own set of risks (basically, it might affect things you are unaware of), though you can reduce those by patching exactly at the import place of your dependency (eg. patch("mymodule.utc_now") vs patch("datetime.datetime.utc_now") — if you are not doing that today, start now! :).
Still, I consider readability the main concern when programming, with testability being second (no surprise they are closely related, as tests will document behaviour precisely). With Python's monkey-patching and mocking, you are at a large risk of producing illegible gibberish, both in tests and code.
If you can at all avoid it, you should! Simple dependency injection by passing dependencies directly in (functions or classes) makes everything explicit and trivial to comprehend (and test).
Unfortunately, the biggest problem is that the world of Python libraries is completely filled with magic side effects, so you sometimes can't effectively avoid doing either of those (it would be too costly).