Golang Mock Basics and Best Practices

Author

Reads 1.2K

A programmer in a modern office working on computer code, showcasing a focused work environment.
Credit: pexels.com, A programmer in a modern office working on computer code, showcasing a focused work environment.

Mocking is a crucial concept in Golang testing, allowing you to isolate dependencies and write more reliable tests.

In Golang, we use the `github.com/golang/mock` package to create mocks. This package provides a simple and efficient way to create mocks for any interface.

A mock object is a fake version of an object that we use in our tests to isolate dependencies. By using mocks, we can test our code in isolation, without relying on external dependencies.

To create a mock, we use the `NewMock` function provided by the `github.com/golang/mock` package. This function takes an interface as an argument and returns a mock object that implements that interface.

A different take: Install Golang Package

Getting Started

The package mock provides a system to mock your objects and verify calls are happening as expected.

To get started, you'll need to familiarize yourself with the package's two main files: doc.go and mock.go. These files contain the necessary information to begin using the mock package.

The mock package is designed to be easy to use, making it a great addition to your Go development toolkit.

Related reading: Golang Go

Go 1.16+

Credit: youtube.com, Golang Made Easy: Learn the Basics in Just 10 Minutes

If you use mockgen in your CI pipeline, it may be more appropriate to fixate on a specific mockgen version.

You should try to keep the library in sync with the version of mockgen used to generate your mocks. This ensures consistency in your testing environment.

This is especially important if you're working with a team, as different versions can lead to confusion and errors.

By keeping mockgen in sync, you'll have a more reliable and efficient testing process.

A fresh viewpoint: Golang Sync

Overview

To get started with mocking in Go, you'll need to understand the basics of the mockgen binary. This binary has two modes of operation: source and reflect.

The mockgen binary is used to create mocks from interfaces, and it's installed with a simple command. Once installed, you can create mocks of interfaces in a source file using a specific command.

This command will generate mock source code of all interfaces to the destination file mock_service.go, and you'll have a NewMock function for every interface you have in the source file.

Consider reading: Go vs Golang

Credit: youtube.com, Getting Started: Overview

You can combine the command with the //go:generate directive to automate the mock generation process. Simply add the command to the first line of your source file, and run go generate to create all your mocks in the project.

To create a mock, you'll need to use the EXPECT() method, which allows you to create calls and configure them. This method is used to set up the mock to return specific values when called with certain arguments.

Here are some ways to use the EXPECT() method:

  • EXPECT() method allowing you to create calls and configure them
  • EXPECT() methods like Call.DoAndReturn (CaptureArguments)
  • EXPECT() methods like Call.DoAndReturn (Latency)

The mock framework for Go, gomock, provides a system by which it is possible to mock your objects and verify calls are happening as expected. The package consists of two files: doc.go and mock.go.

gomock has two primary components: the mock object and the EXPECT() method. The mock object represents the interface being mocked, and the EXPECT() method is used to set up the mock to return specific values when called with certain arguments.

The EXPECT() method can be used to create call order dependencies, which is useful when testing code that relies on the order of method calls. You can use InOrder and/or Call.After to enforce call order dependencies.

Here are some examples of using Call.After to chain expected call order:

  • Call.DoAndReturn (CaptureArguments)
  • Call.DoAndReturn (Latency)

By understanding the basics of the mockgen binary and the EXPECT() method, you'll be well on your way to getting started with mocking in Go.

Install Dependencies

Credit: youtube.com, Installing Dependencies

To get started with mocking in Go, you'll first need to install the required dependencies. Install Go Mock, the mockgen tool, and stretchr/testify package by running the following command in your terminal.

The mockgen package is used to generate mock code, while stretchr/testify is used to enhance test assertions. In our case, it checks if the UserService functions behave as expected.

You'll use the mockgen tool to generate mocks for your interface by running a command in your terminal. This simplifies the process of creating and using mock objects for unit testing in Go, making your tests easier to write and maintain.

Function callbacks are another technique for mocking in Go, allowing you to inject custom behavior into your code during testing. This is particularly useful for mocking functions that don't belong to an interface.

The net/http/httptest package is useful for mocking HTTP requests in Go. It provides functionality such as creating a mock HTTP server and generating mock HTTP requests.

Expand your knowledge: Create a Package in Golang

Configuring Mocks

Credit: youtube.com, Testing with golang and testify - mocking - tutorial part 3

You can configure mocks by using the `NewMock` function from the `github.com/golang/mock/gomock` package. This function returns a new mock object.

To configure a mock, you'll need to define the behavior of the mock object using the `Expect` method. This method takes a function as an argument that specifies the expected behavior.

For example, you can use the `Expect` method to specify that a mock function should return a specific value when called with a certain argument.

Recommended read: Golang Func Type

Reflect Mode

Reflect mode generates mock interfaces by building a program that uses reflection to understand interfaces.

To enable reflect mode, you need to pass two non-flag arguments: an import path, and a comma-separated list of symbols. You can use the current path's package by referring to it with a dot.

The import path helps the program locate the interfaces to be mocked. The comma-separated list of symbols specifies which interfaces to mock.

Explore further: Golang Mode

Types

You can use AnythingOfType to return a value containing the name of the type to check for, which will be matched against the type name returned by reflect.Type.String.

Discover more: Golang Check Type

Woman in focus working on software development remotely on laptop indoors.
Credit: pexels.com, Woman in focus working on software development remotely on laptop indoors.

This function is useful for checking the type of an object, and it's often used in testing scenarios where you need to verify the type of a mock object.

AnythingOfType is an alternative to providing a zero-value of the type to check, which is what IsType does. IsType returns an IsTypeArgument object containing the type to check for, making it a good choice when you need to pass a type to a function.

In some cases, you may need to check the type of a mock object, such as when you're using a Controller to define the scope and lifetime of mock objects. A Controller represents the top-level control of a mock ecosystem and defines the expectations of mock objects.

If you're using a *testing.T object, you don't need to call ctrl.Finish() in your test methods, a feature introduced in go1.14+. This makes it easier to write tests that use Controllers.

Suggestion: T Golang

Example Usage

Credit: youtube.com, Golang Interface Mocking Quick Example

To mock a method in Go, you embed the Mock object into a test object as shown in the example.

The Mock object tracks activity on another object and can be used to verify that the correct methods are being called. You can use the Mock.Called(args...) method to check if a specific method was called with the expected arguments.

To return the appropriate values from a method, you can use the Mock.Called(args...) method in combination with the Int, Error, and Bool methods. These methods are examples of strongly typed getters that take the argument index position.

For your interest: Golang Use Cases

Example Usage

The mock package provides an object, Mock, that tracks activity on another object. It's usually embedded into a test object as shown below.

You can implement methods of an interface by wiring your functions up to call the Mock.Called(args...) method and return the appropriate values. This is a key concept in using the mock package effectively.

Close-up of a person using a tablet on a sunny day outdoors. Ideal for technology and lifestyle themes.
Credit: pexels.com, Close-up of a person using a tablet on a sunny day outdoors. Ideal for technology and lifestyle themes.

To mock a method that saves the name and age of a person and returns the year of their birth or an error, you might write code that calls the Mock.Called(args...) method. The Mock.Called(args...) method takes the argument index position.

The Int, Error, and Bool methods are examples of strongly typed getters that take the argument index position. Given this argument list, you could read them out strongly typed like this.

For objects of your own type, use the generic Arguments.Get(index) method and make a type assertion. This allows you to access the object's properties in a strongly typed way.

Recommended read: Golang Types

TestData

TestData is a special section in Mock objects that holds any data useful for testing. It's completely ignored by Testify, allowing you to do whatever you like with it.

You can store any type of data in TestData, from simple strings to complex objects. This makes it a flexible tool for testing.

The key thing to remember is that TestData is not used by Testify, so you can experiment with different data structures and see what works best for your tests.

Purpose of a Case Study

Adult male programmer working on code at a modern desk setup with a large monitor.
Credit: pexels.com, Adult male programmer working on code at a modern desk setup with a large monitor.

A case study is a practical example that illustrates a concept or solution. It helps to make abstract ideas more concrete and easier to understand.

In the context of mocking, a case study can highlight the importance of decoupling code from external dependencies. By using a mock implementation, you can isolate the code under test and ensure it behaves as expected.

Let's take the example of a logistics company's delivery logic. The goal is to test the code that calls the address service and returns the correct postcode. There are two cases to test: GetPostCode(1) should return 2544TT and GetPostCode(2) should return 1111TK.

The case study shows that using a mock implementation can help you write clean code by reducing coupling. By defining an interface for the address service, you can create a mock type that implements the same interface and use it in your tests.

A key takeaway from this case study is that using an interface allows you to decouple the code from the specific implementation. This makes it easier to write unit tests and ensure the code behaves as expected.

Related reading: Golang Switch Statement

Close-up of a computer screen displaying colorful programming code with depth of field.
Credit: pexels.com, Close-up of a computer screen displaying colorful programming code with depth of field.

Here are the benefits of using a case study:

  • Helps to illustrate complex concepts in a practical way
  • Highlights the importance of decoupling code from external dependencies
  • Shows how to use mocking to isolate code under test
  • Demonstrates the value of using interfaces to reduce coupling

Assertions

Assertions are a crucial part of writing tests in Go, and Gomock provides several functions to make assertions about your mocks.

Assert compares the arguments with the specified objects and fails if they do not exactly match. AssertCalled asserts that the method was called, but can produce a false result when an argument is a pointer type and the underlying value changed after calling the mocked method.

AssertExpectations asserts that everything specified with On and Return was in fact called as expected. Calls may have occurred in any order. AssertNotCalled asserts that the method was not called, but can also produce a false result when an argument is a pointer type and the underlying value changed after calling the mocked method.

In addition to these, Gomock also provides functions to modify failure messages and match arguments. Modifying Failure Messages allows you to customize what is printed when a matcher reports a failure.

Assert Arguments

Computer Program Language Text
Credit: pexels.com, Computer Program Language Text

Asserting the correct arguments is crucial when testing your code. You can use the Assert function to compare the arguments with the specified objects and fail if they don't exactly match.

Gomock has some utility functions to help you with this. For example, you can use the arguments in the calls to make sure that the function you test calls other interfaces with correct arguments. If the arguments don't match, Gomock fails the current test.

You can also use the Called function to tell the mock object that a method has been called, and get an array of arguments to return. This can be useful for asserting that the method was called with the correct arguments.

However, be aware that the Called function can produce a false result when an argument is a pointer type and the underlying value changed after calling the mocked method. This is why it's essential to use the Assert function to ensure that the arguments match exactly.

In some cases, you might want to make sure that the function you test calls other interfaces in a specific order. To achieve this, you can use the After method of the calls or the gomock.InOrder method to arrange calls sequentially.

Anything Of Type

Man Coding on Computers Sitting at Desk
Credit: pexels.com, Man Coding on Computers Sitting at Desk

AnythingOfType returns a special value containing the name of the type to check for. This can be useful when you need to verify that a function call uses the correct type of argument.

You can use AnythingOfType to match the type name returned by reflect.Type.String. For example, if you have a function that takes a string argument, you can use AnythingOfType to check that the argument is indeed a string.

AnythingOfType is a more explicit way to specify the type of argument, compared to using a zero-value of the type. However, it requires the type name to match exactly, so be careful with typos or changes in type names.

Take a look at this: Golang String Template

Call Management

You can arrange calls in order using the After method of the calls or gomock's InOrder method to arrange calls sequentially.

If you want to ensure a mock handler is only called once, you can use the Once method of a call instance.

Unset removes all mock handlers that satisfy the call instance arguments from being called, leaving only the specified handler remaining.

Ordering the Calls

A businessman on a phone call while preparing an online order for shipping in a modern office.
Credit: pexels.com, A businessman on a phone call while preparing an online order for shipping in a modern office.

Calls are not executed in any order by default.

You can use the After method of the calls or gomock.InOrder method to arrange calls sequentially. This allows you to control the order in which your calls are executed.

For example, using the After method, you can specify that one call should be executed after another. This can be useful when you need to test a specific sequence of events.

You can also use gomock.InOrder method to arrange calls in a specific order. This method is a convenient way to ensure that your calls are executed in the correct order.

Unsetting mock handlers can also affect the order of calls. If you unset a handler, it will no longer be called, even if it was previously set to be executed after another call.

Call Twice

The Call Twice method is a powerful tool in call management. It indicates that the mock should only return the value twice.

IT professional working on a computer in a modern office setting, focused on coding and tasks.
Credit: pexels.com, IT professional working on a computer in a modern office setting, focused on coding and tasks.

To use Call Twice effectively, you need to understand its limitations. It does not specify the exact number of times the method should be called, only that it should be called twice.

In some cases, you may need to verify that a method was called a specific number of times. That's where AssertNumberOfCalls comes in. It asserts that the method was called the expected number of times.

However, if you're working with a method that should only be called once, you may want to consider using the Once method instead. It indicates that the mock should only return the value once, which is similar to Call Twice but with a stricter requirement.

But what if you need to verify that a method was called at all? That's where AssertCalled comes in. It asserts that the method was called, but be aware that it can produce a false result if the underlying value changed after calling the mocked method.

Return Value

Photo Of Female Engineer Doing Tests
Credit: pexels.com, Photo Of Female Engineer Doing Tests

You can use the Return method to specify the return arguments for the expectation. This is useful when you want to test how your code handles specific return values.

The Return method can be used multiple times to declare the values to be returned by the mocked function call. This allows you to test different scenarios and edge cases.

To ensure that your mock returns the correct value only twice, you can use the Twice method in conjunction with Return. This is useful when you want to test how your code behaves on the second call.

The AssertNumberOfCalls method can be used to verify that the mocked function was called the expected number of times. This is particularly useful when testing the Return method.

Controller Call

Controller calls are a crucial part of managing calls in your application.

Normally, calls are not executed in any order, so you should arrange them sequentially if needed.

Man with turban working on computer at a desk near window, showcasing concentration and technology use.
Credit: pexels.com, Man with turban working on computer at a desk near window, showcasing concentration and technology use.

You can use the After method of the calls or gomock's InOrder method to arrange calls in order.

The Call method is called by a mock and should not be called by user code. It's not a method you should be using directly.

Similarly, the RecordCall method is also called by a mock and should not be called by user code.

A fresh viewpoint: Golang Source Code

Controller RecordCall

Controller RecordCall is called by a mock and should not be called by user code. It's a method that's used internally by the mock object.

A Controller represents the top-level control of a mock ecosystem, defining the scope and lifetime of mock objects, as well as their expectations. It's safe to call Controller's methods from multiple goroutines.

Each test should create a new Controller and invoke Finish via defer. You no longer need to call ctrl.Finish() in your test methods if you're passing a *testing.T into this function, starting from go1.14+.

Testing

Credit: youtube.com, Test Like a Pro in Go!

Testing is an essential part of writing robust code, especially when working with mocks.

To set up testing, you need to call the Test method on a mock object, which sets the TestingT on which errors will be reported. This is crucial because if errors occur and Test isn't called, they'll cause a panic.

When creating mock objects, it's essential to avoid calling the Test method on an object that will be used in a goroutine other than the one running the test function. This can lead to unexpected behavior and errors.

A Controller is a top-level control of a mock ecosystem that defines the scope and lifetime of mock objects, as well as their expectations. It's safe to call a Controller's methods from multiple goroutines.

Test in 1.2.2

Test in 1.2.2 is a crucial aspect of testing that sets the stage for error reporting.

The Test function sets the TestingT on which errors will be reported, otherwise errors will cause a panic. This is a critical distinction that developers need to be aware of.

When using Test, it should not be called on an object that is going to be used in a goroutine other than the one running the test function. This is to prevent unexpected behavior and errors.

Type Testing T

Workplace with modern laptop with program code on screen
Credit: pexels.com, Workplace with modern laptop with program code on screen

Type Testing T is an interface wrapper around *testing.T. This interface provides a way to test your code in a robust and reliable manner.

The TestingT interface is designed to be used in conjunction with the Test function, which sets the TestingT on which errors will be reported. If the Test function is called on an object that is going to be used in a goroutine other than the one running the test function, it will cause a panic.

To use the TestingT interface, you need to call the Test function to set the TestingT on which errors will be reported. This is a crucial step in testing your code, as it allows you to catch and report any errors that occur during testing.

The IsType function is a useful tool for testing the type of a variable. It returns an IsTypeArgument object containing the type to check for, which can be used to verify that a variable has the correct type.

Controller and Formatter

Credit: youtube.com, Golang gorm mocking

A Controller is a top-level control of a mock ecosystem, defining the scope and lifetime of mock objects, as well as their expectations, and is safe to call from multiple goroutines.

Each test should create a new Controller and invoke Finish via defer, but if you're using go1.14+ and passing a *testing.T into this function, you no longer need to call ctrl.Finish() in your test methods.

GotFormatterAdapter is a function that attaches a GotFormatter to a Matcher, added in version 1.4.0.

WantFormatter modifies the given Matcher's String() method to the given Stringer, allowing for control on how the "Want" is formatted when printing, also added in version 1.4.0.

A different take: Golang Version Manager

Deniz Gursoy on GitHub

Deniz Gursoy is a contributor to the GoMock project on GitHub.

He has made significant contributions to the project, including adding support for mocking interfaces and improving the library's performance.

His work on the project has been widely appreciated by the Go community, and his contributions have helped make GoMock a more powerful and flexible tool for testing Go code.

Deniz Gursoy's GitHub profile shows that he has been actively involved in the Go community for several years, contributing to various open-source projects.

Ismael Anderson

Lead Writer

Ismael Anderson is a seasoned writer with a passion for crafting informative and engaging content. With a focus on technical topics, he has established himself as a reliable source for readers seeking in-depth knowledge on complex subjects. His writing portfolio showcases a range of expertise, including articles on cloud computing and storage solutions, such as AWS S3.

Love What You Read? Stay Updated!

Join our community for insights, tips, and more.