Interface mocking tool for go generate
Interface mocking tool for go generate.
Moq is a tool that generates a struct from any interface. The struct can be used in test code as a mock of the interface.
above: Moq generates the code on the right.
You can read more in the Meet Moq blog post.
To start using latest released version of Moq, just run:
$ go install github.com/matryer/moq@latest
Note that Go 1.18+ is needed for installing from source. For using Moq with older Go versions, use the pre-built binaries published with Moq releases.
…
NOTE: source-dir is the directory where the source code (definition) of the target interface is located.
It needs to be a path to a directory and not the import statement for a Go package.
In a command line:
$ moq -out mocks_test.go . MyInterface
In code (for go generate):
package my
//go:generate moq -out myinterface_moq_test.go . MyInterface
type MyInterface interface {
Method1() error
Method2(i int)
}
Then run go generate for your package.
Mocking interfaces is a nice way to write unit tests where you can easily control the behaviour of the mocked object.
Moq creates a struct that has a function field for each method, which you can declare in your test code.
In this example, Moq generated the EmailSenderMock type:
func TestCompleteSignup(t *testing.T) {
var sentTo string
mockedEmailSender = &EmailSenderMock{
SendFunc: func(to, subject, body string) error {
sentTo = to
return nil
},
}
CompleteSignUp("[email protected]", mockedEmailSender)
callsToSend := len(mockedEmailSender.SendCalls())
if callsToSend != 1 {
t.Errorf("Send was called %d times", callsToSend)
}
if sentTo != "[email protected]" {
t.Errorf("unexpected recipient: %s", sentTo)
}
}
func CompleteSignUp(to string, sender EmailSender) {
// TODO: this
}
The mocked structure implements the interface, where each method calls the associated function field.
.MethodCalls() to track the calls.ResetCalls() to reset calls within an individual mock's contextgo:generate to invoke the moq commandgo/format error, it indicates the generated code was not valid.
You can run the same command with -fmt noop to print the generated source code without attempting to format it.
This can aid in debugging the root cause.The Moq project (and all code) is licensed under the MIT License.
Moq was created by Mat Ryer and David Hernandez, with ideas lovingly stolen from Ernesto Jimenez. Featuring a major refactor by @sudo-suhas, as well as lots of other contributors.
The Moq logo was created by Chris Ryer and is licensed under the Creative Commons Attribution 3.0 License.
No open issues yet, or sync has not completed.