I don’t want to waste your time and let’s hit the point, this article mainly discusses about how to speed up your test experience with mocks.
below are my tricks used in generate.go file:
This is the package we need to install:
go install github.com/vektra/mockery/v2@latest
Mockery provides the ability to easily generate mocks for Golang interfaces. Running go generate will generate mocks for all interfaces within the directories:
The above example shows that interfaces in application.go file were generated in mock_app.go file with all the mocks for all the methods inside the interfaces (check below source code): Intelli-Mall
Use the Generated Mocks in our Tests:
Inside application_test.go file below, we will include a new field in our test case structs so that they can be configured for each test case
In the test function, we must set up the mocks, execute the method, and perform our assertions using **Arrange-Act-Assert **(AAA) pattern. Note that NewMockBasketRepository creates a new instance of MockBasketRepository.
It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
Target func for unit test:
Source Code for application_test.go file: Intelli-Mall
The Mockery package provides constructors for our mocks that take the test variable as input. By utilizing these constructors, there’s no need for extra assertions in the test function’s Assert section. After the test runs, each mock is automatically validated to confirm that the correct number of calls were made to it and that the calls contained the accurate inputs.
In order to perform testing on the AddItem method within the Application, we need to supply an application instance equipped with all the required dependencies. Subsequently, we pass extra parameters to the AddItem method. Since the method solely returns an error, it is most logical to utilize a mock double instead of any of the other options. Without the use of mocks, we would not have the ability to gain insight into the method.
In Summary:
The use of mocks allows you to isolate the code you’re testing from the actual implementations of these dependencies. This isolation ensures that your tests focus on the specific logic of the code being tested rather than the correctness of the external dependencies. While it may seem complex, it’s a good practice for ensuring the reliability of your code.
For example the Load method is mocked so that it won’t be used in BasketRepository but could be used in MockBasketRepository: