• Stars
    star
    1,884
  • Rank 24,441 (Top 0.5 %)
  • Language
    Go
  • License
    MIT License
  • Created about 8 years ago
  • Updated 30 days ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Interface mocking tool for go generate

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 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.

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)
  -rm
    	first remove output file, if it exists
  -skip-ensure
    	suppress mock implementation check, avoid import cycle if mocks generated outside of the tested package
  -stub
    	return zero values when no mock implementation is provided, do not panic
  -version
    	show the version for moq
  -with-resets
    	generate functions to facilitate resetting calls made to a mock

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

Ex: 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 .ResetCalls() to reset calls within an invidual mock's context
  • 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.

More Repositories

1

xbar

Put the output from any script or program into your macOS Menu Bar (the BitBar reboot)
Go
17,483
star
2

xbar-plugins

Plugin repository for xbar (the BitBar reboot)
Shell
2,441
star
3

is

Professional lightweight testing mini-framework for Go.
Go
1,731
star
4

vice

Go channels at horizontal scale (powered by message queues)
Go
1,539
star
5

goblueprints

Source code for Go Programming Blueprints
Go
1,346
star
6

silk

Markdown based document-driven RESTful API testing.
Go
939
star
7

gopherize.me

Gopherize.me app
JavaScript
649
star
8

try

Simple idiomatic retry package for Go
Go
332
star
9

way

HTTP routing for Go 1.7
Go
194
star
10

drop

Dependency-less dependencies for Go.
Go
120
star
11

goscript

Goscript: Runtime execution of Go code.
Go
103
star
12

runner

Interruptable goroutines
Go
99
star
13

respond

Idiomatic API responses for Go.
Go
84
star
14

resync

sync.Once with Reset()
Go
71
star
15

anno

Go package for text annotation.
Go
70
star
16

crunchcrunchcrunchstack

This repo is a starting point for a Go + Svelte.js + TailwindCSS project.
Go
63
star
17

golanguk

Source code for Golang UK talk - August 21st 2015, London.
Go
42
star
18

httperr

HTTP error wrapper
Go
35
star
19

articles

Source code repository for articles on https://medium.com/@matryer
Go
34
star
20

m

Get and Set using JavaScript notation
Go
31
star
21

pangaea

Powerful pre-processor for any kind of text file - powered by JavaScript
Go
29
star
22

version

Command line tool for versioning projects
Go
28
star
23

gae-records

Active Record like wrapper for Google App Engine Datasource in Go
Go
28
star
24

present

Presentations repository
Go
26
star
25

codeform

Easy Go code generation using templates
Go
25
star
26

filedb

File based storage and querying package
Go
23
star
27

mix

Go http.Handler that mixes many files into one request.
Go
13
star
28

captainslog

Logging package for Go
Go
12
star
29

persist

Persist loads and saves Go objects to files
Go
11
star
30

appengine

Example application for Google App Engine (As of November 2018)
Go
10
star
31

gocmds

Template for Go commands
Go
7
star
32

flower

In-process task flow management
Go
6
star
33

PathKit

Path tools for iOS and SpriteKit
Objective-C
6
star
34

oo

oo is the worlds simplest JavaScript OO implementation; for when you need classes and nothing else.
JavaScript
4
star
35

github-downloads

Tool (and Go package) for counting GitHub downloads
Go
4
star
36

str

String parsing package for Go. Converts strings to best guess value type.
Go
4
star
37

isvalid

Ultra simple data parsing and validation in Go
Go
3
star
38

codeform-templates

Repository of Codeform templates
Smarty
3
star
39

funkjs

A sweet selection of JavaScript funktion extensions
JavaScript
2
star
40

tailwindcss-github-theme

TailwindCSS GitHub theme for building GitHub styled apps using Tailwind.
2
star
41

rapid-api

Code for 3.5 hour workshop project at infoShare 2016
1
star
42

testing-in-go

Tutorial repo for Testing in Go talk
1
star
43

berlin-devfest-workshop

Code created during Berlin DevFest Workshop
Go
1
star
44

gimme

old location for github.com/matryer/drop
1
star