counterfeiter is a command-line tool for generating fake implementation of Go interfaces.
One of the best things we can do when writing Go programs is to design our components’ dependencies to be based on local interfaces. By local I mean interfaces which are needed and defined by a given component. Consider the following example: we have a http server, a service component and a database dependency.
|
|
The service component has a database dependency. It may be any kind of external object - client to another service, a cache/database, message queue, whatever. This dependency is expressed as an interface inside the service package. In effect, the service is telling its initialiser: when you create me, please give me an object which implements my service.Storage
interface, cause that’s what I need to execute my functions.
This design has some nice benefits. The service component doesn’t know and care how the storage dependency is implemented. All it knows and cares about is that it has a SomeData() (*storage.Data, error)
function. We can supply whatever object we wish to the service, as long as it implements the interface.
Here comes the counterfeiter
A common use case for using dependency interfaces, is that we can write service component unit tests with 100% coverage, by using a fake implementation of the service.Storage
interface.
counterfeiter
generates fake implementations for interfaces. To generate a fake implementation for service.Storage
, we add a go:generate
directive in the service package.
Another way is to manually run from terminal in the service folder the counterfeiter . Storage
command.
After the command is executed, it creates a fake folder with FakeStorage implementation of the service.Storage
interface. When writing unit tests, we would initialise our service component with the fake object and manipulate its API to cover all code branches and use of the database dependency.
Checkout the counterfeiter docs for more info and examples.