How it works...

The mock objects that have been generated allow tests to specify what arguments are expected, the number of times a function will be called, and what to return. They also allow us to set additional artifacts. For example, we could write to a channel directly if the original function had a similar workflow. The interface_test.go file showcases some examples of using mock objects while calling them in line. Generally, tests will look more like exec_test.go, where we'll want intercept interface function calls performed by our actual code and change their behavior at test time.

The exec_test.go file also showcases how you might use mocked objects in a table-driven test environment. The Any() function means that the mocked function can be called zero or more times, which is great for cases where the code terminates early.

One last trick demonstrated in this recipe is sticking mocked objects into the internal package. This is useful when you need to mock functions declared in packages outside of your own. This allows those methods to be defined in a non _test.go file, but they won't be visible to users of your libraries as they cannot import from the internal package. Generally, it's easier to just stick mocked objects into _test.go files, using the same package name as the tests you're currently writing.