How it works...

This recipe demonstrates how to mock interfaces as well as functions that have been declared as variables. There are also certain libraries that can mimic this patch/restore directly on declared functions, but they bypass a lot of Go's type safety to accomplish that feat. If you need to patch functions from an external package, you may use the following trick:

// Whatever package you wanna patch
import "github.com/package"

// This is patchable using the method described in this recipe
var packageDoSomething = package.DoSomething

For this recipe, we start by setting up our test and using table-driven tests. There's a lot of literature about this technique, such as https://github.com/golang/go/wiki/TableDrivenTests, and I recommend exploring it further. Once our tests are set up, we choose outputs for our mocked functions. In order to mock our interface, our mocked objects define closures that can be rewritten at runtime. The patch/restore technique is applied to change our global function and restore it after each loop. This is thanks to t.Run, which sets up a new function for each loop of the test.

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

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