Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

Interface mocking tool for go generate

License

NotificationsYou must be signed in to change notification settings

matryer/moq

Repository files navigation

moq logobuildGo 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 theMeet 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 witholder Go versions, use the pre-built binaries published withMoq 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 mockSpecifying 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 . MyInterfacetypeMyInterfaceinterface {Method1()errorMethod2(iint)}

Then rungo 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 theEmailSenderMock type:

funcTestCompleteSignup(t*testing.T) {varsentTostringmockedEmailSender=&EmailSenderMock{SendFunc:func(to,subject,bodystring)error {sentTo=toreturnnil},}CompleteSignUp("me@email.com",mockedEmailSender)callsToSend:=len(mockedEmailSender.SendCalls())ifcallsToSend!=1 {t.Errorf("Send was called %d times",callsToSend)}ifsentTo!="me@email.com" {t.Errorf("unexpected recipient: %s",sentTo)}}funcCompleteSignUp(tostring,senderEmailSender) {// 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 individual mock's context
  • Usego:generate to invoke themoq command
  • If Moq fails with ago/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 theMIT License.

Moq was created byMat Ryer andDavid Hernandez, with ideas lovingly stolen fromErnesto Jimenez. Featuring a major refactor by @sudo-suhas, as well as lots of other contributors.

The Moq logo was created byChris Ryer and is licensed under theCreative Commons Attribution 3.0 License.


[8]ページ先頭

©2009-2025 Movatter.jp