Go to file
2016-10-06 15:14:50 +01:00
example added test to prove variadic args aren't working 2016-10-06 11:24:08 +01:00
generate added go:generate example 2016-09-21 22:05:31 +01:00
package/moq fixed call list bug 2016-10-06 11:58:39 +01:00
.gitignore Initial commit 2016-08-29 11:00:17 +01:00
.travis.yml added latest Go version 2016-10-06 15:14:50 +01:00
LICENSE added credit 2016-09-01 10:30:27 +01:00
main.go added go generate example 2016-09-21 22:02:49 +01:00
moq-logo-small.png new logo 2016-09-01 10:13:13 +01:00
moq-logo.png new logo 2016-09-01 10:13:13 +01:00
README.md tiny typos 2016-09-22 09:29:05 +01:00

moq logo

Interface mocking tool for go generate.

By Mat Ryer and David Hernandez, with ideas lovingly stolen from Ernesto Jimenez.

What is Moq?

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.

Installing

To start using Moq, just run go get:

$ go get github.com/matryer/moq

Usage

moq [flags] destination interface [interface2 [interface3 [...]]]
  -out string
    	output file (default stdout)
  -pkg string
    	package name (default will infer)

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.

How to use it

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.

This this example, Moq generated the EmailSenderMock type:

func TestCompleteSignup(t *testing.T) {

	called := false
	var sentTo string 

	mockedEmailSender = &EmailSenderMock{
		SendFunc: func(to, subject, body string) error {
			called = true
			sentTo = to
			return nil
		},
	}

	CompleteSignUp("me@email.com", mockedEmailSender)

	if called == false {
		t.Error("Sender.Send expected")
	}
	if sentTo != "me@email.com" {
		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.

Tips

  • Keep mocked logic inside the test that is using it
  • Only mock the fields you need - it will panic if a nil function gets called
  • Use closured variables inside your test function to capture details about the calls to the methods
  • Use go:generate to invoke the moq command

License

The Moq project (and all code) is licensed under the MIT License.

The Moq logo was created by Chris Ryer and is licensed under the Creative Commons Attribution 3.0 License.