Location>code7788 >text

go: minimalist hands-on mock testing with stretchr/testify

Popularity:755 ℃/2024-10-21 12:09:15

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

  1. GetterTestSuite is the name of the test set.Each methodare invoked as test cases.TestGetter When the function runs, it calls theTestGetterInt
  2. TestGetterInt referenced int beTestSuite, which contains a number of useful assertion functions such asEqual cap (a poem)Nil etc.
  3. After creating a Mock instance, you can use theOn 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:

  1. ("GetApiKey", ).Return("dummy_api_key")GetApiKey has one parameter and returns whatever is passed indummy_api_key
  2. ("GetAllClusterInfo").Maybe().Return(GenerateTestClustersInfo()): If you use theMaybefollowGetAllClusterInfo does not necessarily have to be called; if it is not used theMaybe and the function is not called, the assertion will fail.
  3. ("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.
  4. ((), "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.