
Mocking is an essential tool in Golang testing, allowing you to isolate dependencies and make your tests more reliable.
To effectively use Mockery, you should create a mock object for each dependency, as demonstrated in the example where a mock repository is created to isolate the service's dependency on the database.
A well-structured test suite should have a clear separation of concerns between the service and its dependencies, making it easier to write and maintain tests.
The example of the calculator service demonstrates how to use Mockery to isolate the dependency on the math library, making it possible to test the service independently.
For another approach, see: Golang Test Parallel
What is Mocking?
Mocking is a technique that allows you to isolate dependencies in your code, making it easier to test and maintain.
Mocking relies on interfaces to substitute real implementations with mocks. This is essential for creating effective mocks, as the interfaces need to be present.
Mocking enhances modularity by allowing you to replace real implementations with mocks, making it easier to test and maintain your code.
Mocking enables test isolation by allowing you to control the behavior of your dependencies, making it easier to test individual components of your code.
Getting Started
To get started with GoLang Mockery, you'll need to install it first. You can do this using the command specified in the documentation.
Once installed, you can start using Mockery to generate mocks for your interfaces.
Installation
To get started with Mockery, you'll need to install it first. You can do this using the command "php mockery/bin/mockery install" or by following the instructions on the Mockery website.
The installation process is straightforward, and it will install the latest version of Mockery and its dependencies. This command is the key to unlocking the full potential of Mockery.
By default, Mockery generates mocks in the ./mocks directory, but you can use the output flag to specify a different output directory.
Nephio Make
Nephio Make is a powerful tool that helps you work with Go code in the Nephio repository.
The Makefiles in Nephio repositories containing Go code have targets to support mockery.
You'll find a default-mockery.mk file in the root of the Nephio repository, which is included in Nephio make runs.

There are two targets in default-mockery.mk: install-mockery and generate-mocks.
Run make install-mockery to install mockery in your container runtime or locally if you have no container runtime running.
You only need to run this target once unless you need to reinstall Mockery for some reason.
Run make generate-mocks to generate the mocked implementation of the Go interfaces specified in .mockery.yaml files.
You need to run this target each time an interface that you are mocking changes or whenever you change the contents of a .mockery.yaml file.
Moq
Moq is a popular mocking library for .NET, and it's a crucial tool for any developer working with unit testing.
You can call your solution the "packages: feature" because the config looks like this. This naming convention is helpful for organization and clarity.
To generate mocks for a specific interface, you can use the name flag. This is useful when you need to create a mock object for a particular interface.
Moq allows you to create mock objects that mimic the behavior of real objects, making it easier to test your code.
You can use the name flag to generate mocks for a specific interface, which is a key concept in unit testing.
Worth a look: Golang 测试 Mock
Uber Go Mock
Uber Go Mock is a tool that can be used to generate mock implementations of Go interfaces, but it's not the only option. In fact, the article mentions that it's still slow compared to other tools like Moq and Mockery.
Mockery is actually a more efficient option, especially when used with Makefiles in Nephio repositories. The default-mockery.mk file in the root of the Nephio repository includes targets to support Mockery, making it easy to install and use.
To use Mockery with Makefiles, you can run the make install-mockery target to install Mockery in your container runtime or locally. This only needs to be done once, unless you need to reinstall Mockery for some reason.
The generate-mocks target in the Makefile is what generates the mocked implementation of the Go interfaces specified in .mockery.yaml files. This target looks for .mockery.yaml files in the repository and runs the mockery mock generator on each one it finds.
This allows you to place .mockery.yaml files in either the root of the repository or in subdirectories, giving you flexibility in how you organize your mock implementations.
Generating Mocks
Generating mocks in Go can be done using the name flag to generate mocks for a specific interface. This approach is useful when you need to create mocks for a particular interface.
To generate mocks, you can use a third-party tool like Mockery, which can reduce boilerplate codes and make it easier to create mocking interfaces. This approach is faster and more efficient than creating mocks manually.
You can use the following command to generate mocks using Mockery: `mockery -output ./mocks --keeptree .` This command preserves the directory structure when generating mocks.
By using Mockery, you can easily create maintainable and effective mocks for the interfaces, allowing you to write thorough tests for your Go code.
Here are some key benefits of using Mockery:
- Reduces boilerplate codes
- Collects mocking interface in a common place
- Fast creation of mocking interface
- Many options to mock interface
- Quick integration with CI
Generate mocks for an interface
To generate mocks for an interface, you can use the name flag. This allows you to create mocks for a specific interface.
Using a third-party tool like Mockery can save you time and reduce boilerplate code. With Mockery, you can generate mocks quickly and easily, and it integrates well with Continuous Integration (CI) tools.
The generated mock implementation can be treated as a black box, and you don't need to know the details of its contents to write unit tests. This makes it easier to test your code without worrying about the implementation details of the mock.
To use the mock implementation in unit tests, you can specify input data and the expected outcome for each test. This allows you to control the behavior of the mock and verify that it behaves as expected.
Here's a breakdown of the benefits of using Mockery:
- Reducing boilerplate codes
- Collecting mocking interface in a common
- Very fast creating mocking interface
- Have many options to mock interface
- Quick integration with CI
By using Mockery, you can easily create maintainable and effective mocks for your interfaces, allowing you to write thorough tests for your Go code.
Output Package Name
Generating Mocks requires attention to detail, especially when it comes to specifying the output package name.
You can use the outputpkg flag to set a custom package name for the generated mocks.
This flag allows you to maintain a consistent package structure in your mocks directory, making it easier to navigate and understand your test code.
By specifying a custom package name, you can keep your test code organized and more readable.
This can be particularly useful when working on large projects with complex package structures.
Mocking an Interface
Mocking an Interface is a crucial aspect of writing unit tests in Go. You can create mocking an interface on your own way, but it will increase boilerplate codes in your program.
Using a third-party tool like Mockery can reduce boilerplate codes and make it easier to create maintainable and effective mocks for your interfaces. With Mockery, you can quickly generate mocks for a specific interface using the `name` flag.
Here are some benefits of using Mockery:
- Reducing boilerplate codes
- Collecting mocking interface in a common place
- Very fast creating mocking interface
- Have many options to mock interface
- Quick integration with CI
By using Mockery, you can easily create mocks for your interfaces and write thorough tests for your Go code.
Testing Interface
Testing an interface can be a bit tricky, but with the right tools, it becomes a breeze. You can use the mockery tool to generate mocks for a specific interface, which is a great way to isolate dependencies and make your tests more reliable.
For example, let's say you have an interface DataProvider that represents an external service to fetch data. To create a mock for this interface, you can use the mockery tool with the name flag, as shown in Example 1.
Worth a look: Example Golang
To write unit tests for a component that uses the DataProvider interface, you can use the mock implementation generated by mockery. This is exactly what's done in Example 5, where the unit tests for the Repository Reconciler use the mocks generated above.
When writing tests, it's essential to specify the input data and the expected outcome. You can do this by creating instances of a struct, like the repoTest struct in Example 5, and specifying the fields, arguments, and mocks for each test.
Here are some key benefits of using mockery to generate mocks for your interfaces:
- Reduces boilerplate code
- Collects mocking interfaces in a common place
- Fast creation of mocking interfaces
- Many options to mock interfaces
- Quick integration with CI
By using mockery, you can easily create maintainable and effective mocks for your interfaces, allowing you to write thorough tests for your Go code.
The Solution
One key takeaway is that relying on //go:generate for everything can be a performance pitfall.
Collecting the list of all packages you want to generate mocks for and passing that list into a single call of packages.Load() can be a game-changer. This approach can avoid re-parsing dependencies over and over again, which can significantly reduce runtime.
In a project with 105 interfaces, this approach resulted in a 5x performance increase. With further enhancements, even better results can be achieved.
Users of other code generation projects have reported a whole order of magnitude (~10) increases in performance after switching to a similar approach.
Working with Mocks
To generate mocks for a specific interface, you can use the name flag with Mockery. This will create a mock object that implements the interface, allowing you to control its behavior in your tests.
Mockery integrates with various testing frameworks, including Go's built-in testing package and testify. To use a mock object with Go's testing package, you can create a new instance of the mock object using the new function, and then set up the expected behavior of the mock object using the On method.
You can use the mock object to test your components by creating an instance of the component under test, passing the mock object as an argument, and then calling the method being tested. To check that the result and error match the expected values, you can define variables with the expected values and use an if statement to compare them to the actual values.
Mocking in Unit Tests
Mocking in unit tests is a powerful technique that allows you to isolate dependencies and focus on the behavior of the code you're testing.
You can use Mockery, a popular mocking library for Go, to generate mock implementations of interfaces.
To generate a mock object, you can run the following command: `mockery -name=MyInterface`. This will create a file named `my_interface_mock.go` in the same directory as the original interface file.
The generated mock object will contain a struct that implements the interface and a constructor function that creates an instance of the struct.
You can use the mock object to test your components by setting up the expected behavior of the mock object using the `On` method.
For example, you can set up the mock object to return a specific value for a given method call using `On("MyMethod", mock.Anything)`. Then, you can create an instance of the component under test and call the method being tested.
To check that the result and error match the expected values, you can use an if statement to compare them to the actual values.
Mockery integrates with various testing frameworks, including Go's built-in testing package and testify.
To use the mock object with Go's testing package, you can create a test function that sets up the mock object and calls the method being tested.
For example, you can use the `t.Errorf` function to report an error with a custom message that includes the actual and expected values.
You can also use the `mock.AssertCalled` method to assert that the expected method was called with the expected arguments.
By using Mockery and setting up the expected behavior of the mock object, you can write thorough tests for your Go code and ensure that it behaves as expected.
Include Subdirectories
Including subdirectories can be a game-changer when working with mocks. It allows you to generate mocks recursively, making it easier to cover all the necessary cases.
To include subdirectories, you can use the recursive flag, which is a simple yet effective solution.
Examples and Usage
To get started with Go's Mockery library, you can install it and then use it to generate mock objects for your interfaces.
You can install Mockery using a command, and then generate a mock object for an interface by running a specific command with the interface file path.
To generate a mock object, you can use the Mockery command with the interface file path, and it will create a new file with the mock object implementation.
The mock object will have a struct that implements the interface, and a constructor function that creates an instance of the struct.
You can also use the Mockery configuration file to specify which packages you want to generate mocks for, and where you want the mock files to be generated.
For example, you can create a Mockery configuration file with a list of packages, and specify the package path to the interface you want to generate a mock for.
Mockery can also generate EXPECT() methods for your mocks, which can be useful for testing.
You can use the Mockery command with the interface file path and the EXPECT() method flag to generate EXPECT() methods for your mocks.
The mock object will have a struct that implements the interface, and a constructor function that creates an instance of the struct, just like in the previous examples.
Mockery is a powerful tool for generating mocks in Go, and it can save you a lot of time and effort when writing tests.
You can use Mockery to generate mocks for any interface in your code, and it will create a new file with the mock object implementation.
The generated mock object will have a struct that implements the interface, and a constructor function that creates an instance of the struct, just like in the previous examples.
Mockery also allows you to specify the directory where you want the mock files to be generated, which can be useful for organizing your code.
For example, you can specify the directory where you want the mock files to be generated in the Mockery configuration file.
Mockery is a flexible and powerful tool that can be used in a variety of ways to generate mocks in Go.
You can use Mockery to generate mocks for any interface in your code, and it will create a new file with the mock object implementation.
The generated mock object will have a struct that implements the interface, and a constructor function that creates an instance of the struct, just like in the previous examples.
Mockery can also be used to generate mocks for external packages, which can be useful for testing third-party libraries.
For example, you can use Mockery to generate a mock implementation of the Client interface in the external package sigs.k8s.io/controller-runtime/pkg/client.
Mockery is a great tool for generating mocks in Go, and it can save you a lot of time and effort when writing tests.
You can use Mockery to generate mocks for any interface in your code, and it will create a new file with the mock object implementation.
The generated mock object will have a struct that implements the interface, and a constructor function that creates an instance of the struct, just like in the previous examples.
Templates and Best Practices
The mockery templating framework allows for the use of arbitrary templates, giving them a defined function and data set to work with. This makes it a flexible and powerful tool.
You can port all of your code generation projects to the mockery framework, which has already solved the configuration and parsing problem. This is a significant advantage over other projects like gowrap, which still has performance problems.
The mockery framework can pull in any template, making it a one-stop solution for code generation needs.
Related reading: Golang Test Framework
Salient Features
Mockery is a powerful tool that simplifies the process of creating mock implementations for interfaces. By automating this process, Mockery saves a significant amount of time and effort, especially when dealing with interfaces that have numerous methods.
The command-line interface of Mockery is incredibly straightforward, making it easy to generate mocks with just a few commands. You can customize various aspects of the mock generation process to suit your needs.

Mockery seamlessly integrates with the testify/mock package, allowing you to use assertions like 'On', 'Return', and 'AssertExpectations' with ease. This integration makes it simple to write tests that are both efficient and effective.
One of the most useful features of Mockery is its ability to generate mocks for unexported interfaces. This is particularly useful when you have internal interfaces that you want to mock for testing purposes, but don't want to expose them to the external API of your package.
Specify Package Name
When you're working with mocks, it's essential to specify the package name correctly. This can be done by using the keeptree flag to preserve the directory structure.
Using the keeptree flag is useful to maintain the same package structure in the mocks directory. You can also use the outputpkg flag to set a custom package name for the generated mocks.
The keeptree flag is a simple yet effective way to ensure your mocks have the correct package structure. It's a good practice to use it whenever you're generating mocks.
By specifying the package name correctly, you can avoid confusion and make your code easier to understand and maintain.
Check this out: S Golang
The Utils Package

The Mockery Utils package is a utility package that you can use to initialize your mocks and to define some common fields for your tests.
The MockHelper struct is used to configure a mocked method to expect and return a certain set of arguments.
This struct is passed to the mocked interface during tests, allowing you to control the behavior of a mock.
The MockHelper struct is contained in the mockeryutils-types.go file.
The InitMocks function initializes your mocks for you before a test.
This function takes a given MockHelper array and uses it to initialize the mocks for the specified interface.
The InitMocks function is contained in the mockeryutils.go file.
For your interest: Golang File
Templates
Templates are a crucial part of any code generation project, and Mockery's templating system is no exception.
The .mockery.yaml file can specify which mock implementations Mockery should generate, but for full details, consult the configuration section of the Mockery documentation.
To unify disparate templates, the author of Mockery unified them into a single mockery.tmpl file. This file serves as the foundation for Mockery's templating system.
For another approach, see: Golang Template Example
The author also experimented with incorporating the style of mocks from https://github.com/matryer/moq into Mockery's templating system, which "kind of just worked" after some tinkering.
The Mockery templating framework allows for arbitrary templates to be pulled in and given a defined function and data set to use.
This flexibility makes Mockery a more versatile tool for code generation projects.
Featured Images: pexels.com


