Monkey magic!
Monkey patching is changing a program at runtime, typically by replacing a function or variable.
While this is not a traditional form of dependency injection (DI), it can be used in Go to facilitate testing. In fact, monkey patching can be used to test in ways that are otherwise impossible.
Let's consider a real-world analogy first. Let's say you want to test the effects of a car crash on the human body. You probably wouldn't be volunteering to be the human that was in the car during testing. Nor are you allowed to make changes to the vehicle to facilitate your testing. But you could swap out (monkey patch) the human for a crash test dummy during your test.
The same process holds true for monkey patching in code; the changes ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access