Mockery: a useful code generator for mocking Golang interfaces

Mockery is an awesome tool that can generate mocks from Golang interfaces, which is of great use in unit tests. We can mock functions from an interface with the desired input and output. This is very convenient and helpful when it is difficult to construct the output of some error cases. Also, its output uses the testify framework, which makes it easier to perform granular tests.

  • To install:
    go get

  • A simple example: suppose we have an interface named Example. Run the command mockery -name=Example to get the output in mocks/Example.go. More detailed examples provided at mockery

  • To mock a behavior of an interface:
    mockExample = &mocks.Example{}
    mockExample.On(methodName: "method", input: ...).Return(output: ...)
    You can also append Once() or Times(n) after Return, these methods specifies the order and number of times to call.

Many other useful features are also provided in Mockery, to learn more about it, you can refer to the document and code mockery.