Top Related Projects
Quick Overview
uber-go/mock is a mocking framework for the Go programming language. It generates mock implementations of interfaces that can be used in unit tests, allowing developers to easily create and configure mock objects for testing purposes.
Pros
- Easy to use with a simple API and code generation
- Integrates well with Go's testing package
- Supports method chaining for fluent assertions
- Automatically detects and mocks embedded interfaces
Cons
- Requires code generation, which can add complexity to the build process
- May not cover all edge cases or complex scenarios
- Learning curve for advanced features and customizations
- Can lead to brittle tests if overused or misused
Code Examples
- Generating a mock:
//go:generate mockgen -destination=mock_foo.go -package=main Foo
type Foo interface {
Bar(x int) int
}
- Using a mock in a test:
func TestSomething(t *testing.T) {
mockCtrl := gomock.NewController(t)
defer mockCtrl.Finish()
mockFoo := NewMockFoo(mockCtrl)
mockFoo.EXPECT().Bar(gomock.Any()).Return(42)
// Use mockFoo in your test
}
- Setting up expectations with method chaining:
mockFoo.EXPECT().
Bar(gomock.Eq(10)).
Return(20).
Times(2)
Getting Started
-
Install mockgen:
go install github.com/golang/mock/mockgen@v1.6.0
-
Generate mocks for your interfaces:
mockgen -destination=mock_foo.go -package=main Foo
-
Use the generated mocks in your tests:
import ( "testing" "github.com/golang/mock/gomock" ) func TestExample(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() mockFoo := NewMockFoo(ctrl) // Set up expectations and use the mock }
Competitor Comparisons
A mock code autogenerator for Go
Pros of mockery
- Generates mock implementations automatically from interfaces
- Supports generating mocks for external packages
- Offers a command-line tool for easy integration into build processes
Cons of mockery
- Requires an additional tool installation and setup
- May generate more code than necessary for simple mocks
- Learning curve for configuring and customizing mock generation
Code Comparison
mockery:
//go:generate mockery --name=Repository
type Repository interface {
GetUser(id int) (*User, error)
}
mock:
type MockRepository struct {
mock.Mock
}
func (m *MockRepository) GetUser(id int) (*User, error) {
args := m.Called(id)
return args.Get(0).(*User), args.Error(1)
}
mockery automatically generates mock implementations based on interface definitions, while mock requires manual implementation of mock methods. mockery's approach can save time and reduce boilerplate code, especially for large interfaces. However, mock offers more fine-grained control over mock behavior and may be preferred for simpler use cases or when custom mock logic is required.
Both libraries provide powerful mocking capabilities for Go testing, with mockery focusing on automation and mock emphasizing manual control. The choice between them depends on project requirements, team preferences, and the complexity of the interfaces being mocked.
GoMock is a mocking framework for the Go programming language.
Pros of mock
- Official Go project, potentially more stable and well-maintained
- Wider community adoption and support
- Integrated with Go's testing package
Cons of mock
- Less frequent updates compared to mock
- May lack some advanced features found in mock
- Slightly more verbose syntax in some cases
Code Comparison
mock:
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockObj := NewMockInterface(ctrl)
mockObj.EXPECT().SomeMethod(gomock.Any()).Return(42)
mock:
m := mock.New()
defer m.Assert(t)
mockObj := m.NewMock()
mockObj.On("SomeMethod", mock.Anything).Return(42)
Key Differences
- Syntax: mock uses a more fluent interface, while mock relies on the
EXPECT()
method - Setup: mock requires a controller, mock uses a simpler setup
- Assertions: mock uses
defer ctrl.Finish()
, mock usesdefer m.Assert(t)
- Flexibility: mock offers more advanced matching and stubbing options
- Performance: mock may have a slight edge in large-scale mocking scenarios
Both libraries are widely used and capable of handling most mocking needs in Go projects. The choice often comes down to personal preference, project requirements, and existing codebase conventions.
A toolkit with common assertions and mocks that plays nicely with the standard library
Pros of testify
- Comprehensive suite of testing tools beyond mocking (assertions, suite support)
- More intuitive API for writing assertions and mocks
- Active development and community support
Cons of testify
- Larger dependency footprint
- May be overkill for projects only needing mocking functionality
- Learning curve for utilizing all features effectively
Code Comparison
testify:
mock := new(MyMockedObject)
mock.On("DoSomething", 123).Return(true, nil)
// use mock in test
mock:
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mock := NewMockMyInterface(ctrl)
mock.EXPECT().DoSomething(123).Return(true, nil)
// use mock in test
Summary
testify offers a more comprehensive testing toolkit, including assertions and suite support, making it suitable for projects requiring extensive testing features. It has an intuitive API but comes with a larger footprint.
mock focuses specifically on mocking, providing a lightweight solution for projects primarily needing mock objects. It has a slightly more verbose syntax but offers fine-grained control over mock expectations.
Choose testify for full-featured testing needs or mock for a focused, lightweight mocking solution in Go projects.
Interface mocking tool for go generate
Pros of moq
- Generates mock implementations directly from interface definitions
- Simpler setup and usage, with no runtime dependencies
- Produces clean, readable mock code that's easy to understand and modify
Cons of moq
- Less flexible than mock for complex mocking scenarios
- Doesn't support method chaining or advanced expectation setting
- Limited built-in assertion capabilities compared to mock
Code Comparison
moq:
func TestSomething(t *testing.T) {
m := &UserServiceMock{
GetFunc: func(id int) (*User, error) {
return &User{Name: "John"}, nil
},
}
// Use m.Get(1) in your test
}
mock:
func TestSomething(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
m := NewMockUserService(ctrl)
m.EXPECT().Get(1).Return(&User{Name: "John"}, nil)
// Use m.Get(1) in your test
}
Both moq and mock are popular mocking libraries for Go, each with its own strengths. moq focuses on simplicity and generates easy-to-read mock implementations, while mock offers more advanced features and flexibility for complex mocking scenarios. The choice between them depends on the specific needs of your project and testing requirements.
Monkey patching in Go
Pros of monkey
- Allows mocking of static functions and methods without changing the source code
- Can patch functions at runtime, enabling more flexible testing scenarios
- Supports mocking of built-in Go functions and standard library methods
Cons of monkey
- Uses unsafe runtime patching, which can lead to unpredictable behavior
- May not work correctly with inlined functions or optimized code
- Limited support for concurrent testing scenarios
Code Comparison
monkey:
patch := monkey.Patch(fmt.Println, func(a ...interface{}) (n int, err error) {
return 0, nil
})
defer patch.Unpatch()
mock:
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockObj := NewMockInterface(ctrl)
mockObj.EXPECT().SomeMethod(gomock.Any()).Return(42)
Key Differences
- monkey focuses on runtime patching of functions, while mock generates mock implementations of interfaces
- mock requires code generation and interface-based design, whereas monkey can work with existing code
- mock is generally considered safer and more idiomatic for Go testing, but less flexible than monkey
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
gomock
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 project originates from Google's golang/mock
repo. Unfortunately, Google
no longer maintains this project, and given the heavy usage of gomock project
within Uber, we've decided to fork and maintain this going forward at Uber.
Contributions are welcome in the form of GitHub issue or PR!
Supported Go Versions
go.uber.org/mock supports all Go versions supported by the official Go Release Policy. That is, the two most recent releases of Go.
Installation
Install the mockgen
tool.
go install go.uber.org/mock/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
has two modes of operation: source and reflect.
Source mode
Source mode generates mock interfaces from a source file. It is enabled by using the -source flag. Other flags that may be useful in this mode are -imports and -aux_files.
Example:
mockgen -source=foo.go [other options]
Reflect mode
Reflect mode generates mock interfaces by building a program that uses reflection to understand interfaces. It is enabled 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:
-
-source
: A file containing interfaces to be mocked. -
-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 ismock_
concatenated with the package of the input file. -
-imports
: A list of explicit imports that should be used in the resulting source code, specified as a comma-separated list of elements of the formfoo=bar/baz
, wherebar/baz
is the package being imported andfoo
is the identifier to use for the package in the generated source code. -
-aux_files
: A list of additional files that should be consulted to resolve e.g. embedded interfaces defined in a different file. This is specified as a comma-separated list of elements of the formfoo=bar/baz.go
, wherebar/baz.go
is the source file andfoo
is the package name of that file used by the -source file. -
-build_flags
: (reflect mode only) Flags passed verbatim togo build
. -
-mock_names
: A list of custom names for generated mocks. This is specified as a comma-separated list of elements of the formRepository=MockSensorRepository,Endpoint=MockSensorEndpoint
, whereRepository
is the interface name andMockSensorRepository
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. -
-exec_only
: (reflect mode) If set, execute this reflection program. -
-prog_only
: (reflect mode) Only generate the reflection program; write it to stdout and exit. -
-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 original file (source mode) or interface names (reflect mode) comment if true. (default true) -
-typed
: Generate Type-safe 'Return', 'Do', 'DoAndReturn' function. (default false) -
-exclude_interfaces
: Comma-separated names of interfaces to be excluded
For an example of the use of mockgen
, see the sample/
directory. In simple
cases, you will need only the -source
flag.
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
.
Top Related Projects
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot