gomock

module
v0.0.0-...-5ead146 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 19, 2026 License: Apache-2.0

README

gomock

Build Status Go Reference

gomock is a mocking framework for the Go programming language. It integrates well with Go's built-in testing package, but can be used in other contexts too.

This is a Canonical fork of Uber's gomock, which was itself a fork of Google's golang/mock. This fork moves forward with a simplified approach to mock generation, using and supporting generics.

Installation

Install the mockgen tool.

go install github.com/canonical/gomock/mockgen@latest

To ensure it was installed correctly, use:

mockgen -version

If that fails, make sure your GOPATH/bin is in your PATH. You can add it with:

export PATH=$PATH:$(go env GOPATH)/bin

Running mockgen

mockgen generates mock implementations of Go interfaces by passing two non-flag arguments: an import path, and a comma-separated list of symbols. You can use "." to refer to the current path's package.

Example:

mockgen database/sql/driver Conn,Driver

# Convenient for `go:generate`.
mockgen . Conn,Driver
Flags

The mockgen command is used to generate source code for a mock class given a Go source file containing interfaces to be mocked. It supports the following flags:

  • -destination: A file to which to write the resulting source code. If you don't set this, the code is printed to standard output.

  • -package: The package to use for the resulting mock class source code. If you don't set this, the package name is mock_ concatenated with the package of the input file.

  • -build_flags: Flags passed verbatim to go list.

  • -build_constraint: If non-empty, added as //go:build <constraint> to the generated file.

  • -mock_names: A list of custom names for generated mocks. This is specified as a comma-separated list of elements of the form Repository=MockSensorRepository,Endpoint=MockSensorEndpoint, where Repository is the interface name and MockSensorRepository is the desired mock name (mock factory method and mock recorder will be named after the mock). If one of the interfaces has no custom name specified, then default naming convention will be used.

  • -self_package: The full package import path for the generated code. The purpose of this flag is to prevent import cycles in the generated code by trying to include its own package. This can happen if the mock's package is set to one of its inputs (usually the main one) and the output is stdio so mockgen cannot detect the final output package. Setting this flag will then tell mockgen which import to exclude.

  • -copyright_file: Copyright file used to add copyright header to the resulting source code.

  • -debug_parser: Print out parser results only.

  • -write_command_comment: Writes the command used to generate the mock as a comment if true. (default true)

  • -write_package_comment: Writes package documentation comment (godoc) if true. (default true)

  • -write_generate_directive: Add //go:generate directive to regenerate the mock. (default false)

  • -write_source_comment: Writes source interface names comment if true. (default true)

For an example of the use of mockgen, see the sample/ directory.

Building Mocks

type Foo interface {
  Bar(x int) int
}

func SUT(f Foo) {
 // ...
}

func TestFoo(t *testing.T) {
  ctrl := gomock.NewController(t)

  m := NewMockFoo(ctrl)

  // Asserts that the first and only call to Bar() is passed 99.
  // Anything else will fail.
  m.
    EXPECT().
    Bar(gomock.Eq(99)).
    Return(101)

  SUT(m)
}

Building Stubs

type Foo interface {
  Bar(x int) int
}

func SUT(f Foo) {
 // ...
}

func TestFoo(t *testing.T) {
  ctrl := gomock.NewController(t)

  m := NewMockFoo(ctrl)

  // Does not make any assertions. Executes the anonymous functions and returns
  // its result when Bar is invoked with 99.
  m.
    EXPECT().
    Bar(gomock.Eq(99)).
    DoAndReturn(func(_ int) int {
      time.Sleep(1*time.Second)
      return 101
    }).
    AnyTimes()

  // Does not make any assertions. Returns 103 when Bar is invoked with 101.
  m.
    EXPECT().
    Bar(gomock.Eq(101)).
    Return(103).
    AnyTimes()

  SUT(m)
}

Modifying Failure Messages

When a matcher reports a failure, it prints the received (Got) vs the expected (Want) value.

Got: [3]
Want: is equal to 2
Expected call at user_test.go:33 doesn't match the argument at index 1.
Got: [0 1 1 2 3]
Want: is equal to 1
Modifying Want

The Want value comes from the matcher's String() method. If the matcher's default output doesn't meet your needs, then it can be modified as follows:

gomock.WantFormatter(
  gomock.StringerFunc(func() string { return "is equal to fifteen" }),
  gomock.Eq(15),
)

This modifies the gomock.Eq(15) matcher's output for Want: from is equal to 15 to is equal to fifteen.

Modifying Got

The Got value comes from the object's String() method if it is available. In some cases the output of an object is difficult to read (e.g., []byte) and it would be helpful for the test to print it differently. The following modifies how the Got value is formatted:

gomock.GotFormatterAdapter(
  gomock.GotFormatterFunc(func(i any) string {
    // Leading 0s
    return fmt.Sprintf("%02d", i)
  }),
  gomock.Eq(15),
)

If the received value is 3, then it will be printed as 03.

Directories

Path Synopsis
Package gomock is a mock framework for Go.
Package gomock is a mock framework for Go.
internal/gencall command
gencall generates typed call wrappers for the gomock package.
gencall generates typed call wrappers for the gomock package.
internal/mock_gomock
Package mock_gomock is a generated GoMock package.
Package mock_gomock is a generated GoMock package.
MockGen generates mock implementations of Go interfaces.
MockGen generates mock implementations of Go interfaces.
internal/tests/add_generate_directive
Package add_generate_directive makes sure output places the go:generate command as a directive in the generated code.
Package add_generate_directive makes sure output places the go:generate command as a directive in the generated code.
internal/tests/add_generate_directive/mockgen/internal/tests/add_generate_directive
Package add_generate_directive is a generated GoMock package.
Package add_generate_directive is a generated GoMock package.
Package add_generate_directive is a generated GoMock package.
Package add_generate_directive is a generated GoMock package.
internal/tests/alias/mock
Package mock is a generated GoMock package.
Package mock is a generated GoMock package.
internal/tests/aux_imports_embedded_interface
Package bugreport is a generated GoMock package.
Package bugreport is a generated GoMock package.
internal/tests/build_flags/mock1
Package mock_build_flags is a generated GoMock package.
Package mock_build_flags is a generated GoMock package.
internal/tests/build_flags/mock2
Package mock_build_flags is a generated GoMock package.
Package mock_build_flags is a generated GoMock package.
internal/tests/const_array_length
Package const_length is a generated GoMock package.
Package const_length is a generated GoMock package.
internal/tests/copyright_file
Package empty_interface is a generated GoMock package.
Package empty_interface is a generated GoMock package.
internal/tests/defined_import_local_name
Package defined_import_local_name is a generated GoMock package.
Package defined_import_local_name is a generated GoMock package.
internal/tests/dot_imports
Package dot_imports is a generated GoMock package.
Package dot_imports is a generated GoMock package.
internal/tests/empty_interface
Package empty_interface is a generated GoMock package.
Package empty_interface is a generated GoMock package.
internal/tests/extra_import
Package extra_import makes sure output does not import it.
Package extra_import makes sure output does not import it.
internal/tests/generated_identifier_conflict
Package bugreport is a generated GoMock package.
Package bugreport is a generated GoMock package.
internal/tests/import_aliased
Package import_aliased is a generated GoMock package.
Package import_aliased is a generated GoMock package.
internal/tests/import_collision/p2/mocks
Package internalpackage is a generated GoMock package.
Package internalpackage is a generated GoMock package.
internal/tests/import_embedded_interface
Package bugreport is a generated GoMock package.
Package bugreport is a generated GoMock package.
internal/tests/import_source
Package mock_source is a generated GoMock package.
Package mock_source is a generated GoMock package.
internal/tests/import_source/definition
Package source is a generated GoMock package.
Package source is a generated GoMock package.
internal/tests/missing_import/output
Package source is a generated GoMock package.
Package source is a generated GoMock package.
internal/tests/missing_import/source
Package source makes sure output imports its.
Package source makes sure output imports its.
internal/tests/mock_name/mocks
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.
internal/tests/overlapping_methods
Package overlap is a generated GoMock package.
Package overlap is a generated GoMock package.
internal/tests/package_mode/mock
Package mock is a generated GoMock package.
Package mock is a generated GoMock package.
internal/tests/sanitization/mockout
Package mockout is a generated GoMock package.
Package mockout is a generated GoMock package.
internal/tests/self_package
Package core is a generated GoMock package.
Package core is a generated GoMock package.
internal/tests/typed_inorder
Package typed_inorder is a generated GoMock package.
Package typed_inorder is a generated GoMock package.
internal/tests/unexported_method
Package bugreport is a generated GoMock package.
Package bugreport is a generated GoMock package.
internal/tests/vendor_dep
Package vendor_dep is a generated GoMock package.
Package vendor_dep is a generated GoMock package.
internal/tests/vendor_dep/source_mock_package
Package mock_vendor_dep is a generated GoMock package.
Package mock_vendor_dep is a generated GoMock package.
internal/tests/vendor_pkg
Package vendor_pkg is a generated GoMock package.
Package vendor_pkg is a generated GoMock package.
model
Package model contains the data model necessary for generating mock implementations.
Package model contains the data model necessary for generating mock implementations.
Package user is an example package with an interface.
Package user is an example package with an interface.
concurrent
Package concurrent demonstrates how to use gomock with goroutines.
Package concurrent demonstrates how to use gomock with goroutines.
concurrent/mock
Package mock_concurrent is a generated GoMock package.
Package mock_concurrent is a generated GoMock package.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL