library installation
First, install Mockery, the Mock class generation tool:
go install /vektra/mockery/[email protected]
In fact, you can also create Mock classes manually.
Generate Mock Classes
Let's say you're ininternal/metrics
There are interfaces defined under the package as follows:
package metrics
type Getter[T any] interface {
Get() (T, error)
}
In the project root directory, you can use the following command to generate Mock classes:
mockery --name=Getter --dir=internal/metrics
The generated Mock class will be in themocks
directory of the Documentation.
Writing Use Cases
package metrics
import (
"testing"
mocks "xxx/mock/internal_/metrics"
"/stretchr/testify/suite"
)
type GetterTestSuite struct {
}
func TestGetter(t *) {
(t, new(GetterTestSuite))
}
func (t *GetterTestSuite) TestGetterInt() {
().Logf("TestGetterInt run")
getter := new([int])
("Get").Return(1, nil)
val, err := ()
(err)
(1, val)
}
clarification:
- GetterTestSuite is the name of the test set.Each methodare invoked as test cases.TestGetter When the function runs, it calls theTestGetterInt。
-
TestGetterInt referenced in
t
beTestSuite
, which contains a number of useful assertion functions such asEqual
cap (a poem)Nil
etc. - After creating a Mock instance, you can use the
On
method to mark the method's corresponding return value. Assuming that theGet
Methods can be passed parameters, then you can choose different return values depending on the parameters.
Mock Common Usage:
suppose that...mockObj
is an instance of the Mock class:
-
("GetApiKey", ).Return("dummy_api_key")
:GetApiKey
has one parameter and returns whatever is passed indummy_api_key
。 -
("GetAllClusterInfo").Maybe().Return(GenerateTestClustersInfo())
: If you use theMaybe
followGetAllClusterInfo
does not necessarily have to be called; if it is not used theMaybe
and the function is not called, the assertion will fail. -
("RunCleanup", true, true).Once().Return(nil, nil)
:RunCleanup
There are two arguments, so you need to pass two Mock values into it.Once
Indicates that this function should only be called once. -
((), "RunCleanup", 4)
: You can check the number of times a method has been called.
With these usages, the user has full control over the behavior of each method of the Mock class and performs a number of checks to refine the overall test.