Coder Social home page Coder Social logo

moq's Introduction

moq logo build Go Report Card

Interface mocking tool for go generate.

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.

Preview

above: Moq generates the code on the right.

You can read more in the Meet Moq blog post.

Installing

To start using latest released version of Moq, just run:

Go version < 1.16

$ go get github.com/matryer/moq

Go 1.16+

$ go install github.com/matryer/moq@latest

Usage

moq [flags] source-dir interface [interface2 [interface3 [...]]]
	-fmt string
		go pretty-printer: gofmt, goimports or noop (default gofmt)
	-out string
		output file (default stdout)
	-pkg string
		package name (default will infer)
	-stub
		return zero values when no mock implementation is provided, do not panic
	-skip-ensure
		suppress mock implementation check, avoid import cycle if mocks
		generated outside of the tested package

Specifying an alias for the mock is also supported with the format 'interface:alias'

Example: moq -pkg different . MyInterface:MyMock

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.

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.

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.

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
  • Name arguments in the interface for a better experience
  • Use closured variables inside your test function to capture details about the calls to the methods
  • Use .MethodCalls() to track the calls
  • Use go:generate to invoke the moq command
  • If Moq fails with a go/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.

License

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.

moq's People

Contributors

breml avatar cgorenflo avatar dahernan avatar dedalusj avatar djui avatar dpetersen avatar fvosberg avatar haraldnordgren avatar ivansafonov avatar kl09 avatar maneac avatar matryer avatar meamidos avatar metalrex100 avatar pdrum avatar piotrrojek avatar romanlevin avatar soniah avatar steveoc64 avatar sudo-suhas avatar tprebs avatar uji avatar umputun avatar veloek avatar warmans avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.