Mocking using the standard library
In Go, mocking typically means implementing an interface with a test version that allows you to control runtime behavior from tests. It may also refer to mocking functions and methods, for which we'll explore another trick in this recipe. This trick uses the Patch
and Restore
functions defined at https://play.golang.org/p/oLF1XnRX3C.
In general, it's better to compose code so that you can use interfaces frequently and the code is in small testable chunks. Code that contains lots of branching conditions or deeply nested logic can be tricky to test and tests tend to be more brittle at the end. This is because a developer will need to keep track of more mock objects, patches, return values, and states within their tests.
Getting ready
Configure your environment according to these steps:
- Download and install Go on your operating system from https://golang.org/doc/install and configure your
GOPATH
environment variable. - Open a terminal/console application.
- Navigate...