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 only exist during the test and in many cases can be applied with little impact on the production code. 

A quick note for those of you familiar with dynamic languages such as Ruby, Python, and JavaScript: it is possible to monkey patch individual class methods, and in some cases, patch the standard library. Go only offers us the ability to patch variables, which can be objects or functions, as we will see in this chapter.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.172.56