•  


GitHub - matryer/moq: Interface mocking tool for go generate
Skip to content

matryer/moq

Repository files navigation

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
(
"me@email.com"
, 
mockedEmailSender
)

	
callsToSend
 :=
 len
(
mockedEmailSender
.
SendCalls
())
	
if
 callsToSend
 !=
 1
 {
		
t
.
Errorf
(
"Send was called %d times"
, 
callsToSend
)
	}
	
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
  • 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 .

- "漢字路" 한글한자자동변환 서비스는 교육부 고전문헌국역지원사업의 지원으로 구축되었습니다.
- "漢字路" 한글한자자동변환 서비스는 전통문화연구회 "울산대학교한국어처리연구실 옥철영(IT융합전공)교수팀"에서 개발한 한글한자자동변환기를 바탕하여 지속적으로 공동 연구 개발하고 있는 서비스입니다.
- 현재 고유명사(인명, 지명등)을 비롯한 여러 변환오류가 있으며 이를 해결하고자 많은 연구 개발을 진행하고자 하고 있습니다. 이를 인지하시고 다른 곳에서 인용시 한자 변환 결과를 한번 더 검토하시고 사용해 주시기 바랍니다.
- 변환오류 및 건의,문의사항은 juntong@juntong.or.kr로 메일로 보내주시면 감사하겠습니다. .
Copyright ⓒ 2020 By '전통문화연구회(傳統文化硏究會)' All Rights reserved.
 한국   대만   중국   일본