Top Related Projects
GoMock is a mocking framework for the Go programming language.
A toolkit with common assertions and mocks that plays nicely with the standard library
Monkey patching in Go
HTTP mocking for Golang
HTTP traffic mocking and testing made easy in Go ༼ʘ̚ل͜ʘ̚༽
Quick Overview
Mockery is a mocking framework for the Go programming language. It provides a simple and intuitive way to create and manage mocks for unit testing, allowing developers to isolate their code from external dependencies and focus on testing the specific behavior of their application.
Pros
- Simplicity: Mockery provides a straightforward and easy-to-use API for creating and managing mocks, making it accessible to developers of all skill levels.
- Flexibility: Mockery supports a wide range of use cases, from simple function mocks to complex interface mocks, allowing developers to tailor their testing approach to their specific needs.
- Extensibility: Mockery can be extended with custom matchers and assertions, enabling developers to create more sophisticated and domain-specific mocks.
- Integration: Mockery integrates well with other popular Go testing frameworks, such as Testify, making it easy to incorporate into existing test suites.
Cons
- Limited Reflection Support: Mockery relies on code generation, which can be less flexible than runtime reflection-based mocking approaches, especially for complex or dynamic interfaces.
- Potential Overhead: The code generation process can add some overhead to the build and test process, which may be a concern for projects with large or complex test suites.
- Dependency on Code Generation: Mockery's reliance on code generation means that developers need to be comfortable with the tool's workflow and configuration, which may be a barrier for some teams.
- Limited Ecosystem: Compared to mocking frameworks in other languages, the Mockery ecosystem is relatively small, with fewer pre-built mocks and integrations available.
Code Examples
Here are a few examples of how to use Mockery in your Go code:
Creating a Simple Mock
type MyService interface {
DoSomething(arg string) error
}
func TestMyService(t *testing.T) {
// Create a mock instance of MyService
mock := mocks.NewMyServiceMock(t)
// Set up expectations for the mock
mock.On("DoSomething", "test").Return(nil)
// Call the method on the mock
err := mock.DoSomething("test")
assert.NoError(t, err)
// Verify that the mock was called as expected
mock.AssertExpectations(t)
}
Mocking an Interface with Custom Matchers
type MyInterface interface {
DoSomething(arg1 int, arg2 string) (int, error)
}
func TestMyInterface(t *testing.T) {
// Create a mock instance of MyInterface
mock := mocks.NewMyInterfaceMock(t)
// Set up expectations with a custom matcher
mock.On("DoSomething", mock.MatchedBy(func(arg1 int) bool { return arg1 > 0 }), "test").Return(42, nil)
// Call the method on the mock
result, err := mock.DoSomething(1, "test")
assert.NoError(t, err)
assert.Equal(t, 42, result)
// Verify that the mock was called as expected
mock.AssertExpectations(t)
}
Mocking a Method with Side Effects
type MyStruct struct {
Value int
}
func (m *MyStruct) DoSomething(arg int) error {
m.Value += arg
return nil
}
func TestMyStruct(t *testing.T) {
// Create a mock instance of MyStruct
mock := mocks.NewMyStructMock(t)
// Set up expectations with a side effect
mock.On("DoSomething", 10).Run(func(args mock.Arguments) {
// Update the mock's internal state
m := args.Get(0).(*MyStruct)
m.Value += 10
}).Return(nil)
// Call the method on the mock
obj := &MyStruct{}
err := mock.DoSomething(10)
assert.NoError(t, err)
assert.Equal(t, 10, obj.Value)
// Verify that
Competitor Comparisons
GoMock is a mocking framework for the Go programming language.
Pros of mock
- Simpler API and easier to use for basic mocking scenarios
- Integrated with Go's testing package, allowing for seamless integration
- Lightweight and has fewer dependencies
Cons of mock
- Less flexible for complex mocking scenarios
- Fewer features compared to mockery (e.g., no built-in mock generation from interfaces)
- May require more manual setup for certain use cases
Code Comparison
mockery:
type MyInterface interface {
DoSomething(int) (string, error)
}
mock := new(MyMock)
mock.On("DoSomething", 1).Return("result", nil)
mock:
type MyInterface interface {
DoSomething(int) (string, error)
}
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mock := NewMockMyInterface(ctrl)
mock.EXPECT().DoSomething(1).Return("result", nil)
Summary
Both mockery and mock are popular mocking libraries for Go, each with its own strengths. mockery offers more features and flexibility, especially for complex scenarios, while mock provides a simpler API and tighter integration with Go's testing package. The choice between them depends on the specific needs of your project and personal preference.
A toolkit with common assertions and mocks that plays nicely with the standard library
Pros of testify
- Comprehensive testing toolkit with assertions, mocks, and suites
- Well-established and widely adopted in the Go community
- Extensive documentation and examples
Cons of testify
- Larger API surface area to learn
- May be overkill for simple projects
- Less focused on mocking compared to mockery
Code Comparison
testify:
import "github.com/stretchr/testify/mock"
type MyMockedObject struct {
mock.Mock
}
func (m *MyMockedObject) DoSomething(number int) (bool, error) {
args := m.Called(number)
return args.Bool(0), args.Error(1)
}
mockery:
//go:generate mockery --name=MyInterface
type MyInterface interface {
DoSomething(number int) (bool, error)
}
// Usage in tests
mock := NewMockMyInterface(t)
mock.On("DoSomething", 123).Return(true, nil)
Summary
testify offers a comprehensive testing toolkit, while mockery focuses specifically on generating mocks. testify is more widely adopted and provides a broader set of tools, but mockery excels in its specialized area of mock generation. The choice between the two depends on project requirements and personal preference for API design and functionality.
Monkey patching in Go
Pros of Monkey
- Allows patching of unexported functions and methods
- Can modify behavior of existing functions at runtime
- No code generation required, works directly with existing code
Cons of Monkey
- Potentially unsafe, as it modifies runtime behavior
- May cause unexpected side effects in production code
- Limited support for concurrent code
Code Comparison
Mockery:
func TestSomething(t *testing.T) {
mockObj := new(MyMockedObject)
mockObj.On("DoSomething", 123).Return(true, nil)
// Use mockObj in your test
}
Monkey:
func TestSomething(t *testing.T) {
patch := monkey.Patch(DoSomething, func(n int) (bool, error) {
return true, nil
})
defer patch.Unpatch()
// Test code using patched DoSomething
}
Summary
Mockery is a more traditional mocking framework that generates mock objects, while Monkey uses runtime patching to modify existing functions. Mockery is generally safer and more suitable for production code, but Monkey offers more flexibility in certain scenarios, especially when dealing with unexported or third-party code. The choice between the two depends on specific testing requirements and the level of control needed over the mocked behavior.
HTTP mocking for Golang
Pros of httpmock
- Specifically designed for mocking HTTP requests, making it more focused and potentially easier to use for HTTP-related testing
- Provides a simple and intuitive API for setting up mock HTTP responses
- Supports both stubbing and verification of HTTP requests
Cons of httpmock
- Limited to HTTP mocking, whereas mockery is a more general-purpose mocking tool
- May require additional setup for non-HTTP related tests
- Less flexibility for complex mocking scenarios outside of HTTP interactions
Code Comparison
httpmock:
httpmock.Activate()
defer httpmock.DeactivateAndReset()
httpmock.RegisterResponder("GET", "https://api.example.com/users",
httpmock.NewStringResponder(200, `[{"id": 1, "name": "John"}]`))
mockery:
mock := new(mocks.MyInterface)
mock.On("SomeMethod", mock.Anything).Return(42, nil)
// Use the mock in your test
result, err := mock.SomeMethod("input")
Summary
httpmock is a specialized tool for mocking HTTP requests, offering a straightforward API for HTTP-related testing. It excels in simplicity for HTTP mocking but is limited to that specific use case. mockery, on the other hand, is a more versatile mocking tool that can handle various interfaces and methods, providing greater flexibility for different testing scenarios beyond HTTP interactions.
HTTP traffic mocking and testing made easy in Go ༼ʘ̚ل͜ʘ̚༽
Pros of gock
- Simpler API for HTTP mocking, focusing specifically on HTTP requests and responses
- Built-in support for JSON matching and custom matchers
- Easier to set up and use for HTTP-specific mocking scenarios
Cons of gock
- Limited to HTTP mocking, while mockery is a more general-purpose mocking tool
- Less flexibility for complex mocking scenarios outside of HTTP requests
- Smaller community and fewer contributions compared to mockery
Code Comparison
gock:
defer gock.Off()
gock.New("https://api.example.com").
Get("/users").
Reply(200).
JSON(map[string]string{"name": "John"})
mockery:
mock := new(MockHTTPClient)
mock.On("Get", "https://api.example.com/users").
Return(&http.Response{
StatusCode: 200,
Body: ioutil.NopCloser(bytes.NewReader([]byte(`{"name":"John"}`))),
}, nil)
Summary
gock is more specialized for HTTP mocking, offering a simpler API and built-in features for HTTP-specific scenarios. mockery, on the other hand, is a more versatile mocking tool that can be used for various types of mocking beyond HTTP requests. The choice between the two depends on the specific needs of your project and the complexity of your mocking requirements.
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
mockery
mockery provides the ability to easily generate mocks for Golang interfaces using the stretchr/testify/mock package. It removes the boilerplate coding required to use mocks.
Documentation
Documentation is found at out GitHub Pages site.
Development
taskfile.dev is used for build tasks. Initialize all go build tools:
go mod download -x
You can run any of the steps listed in Taskfile.yml
:
$ task test
task: [test] go test -v -coverprofile=coverage.txt ./...
Stargazers
Top Related Projects
GoMock is a mocking framework for the Go programming language.
A toolkit with common assertions and mocks that plays nicely with the standard library
Monkey patching in Go
HTTP mocking for Golang
HTTP traffic mocking and testing made easy in Go ༼ʘ̚ل͜ʘ̚༽
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