Go Mock 接口測(cè)試 單元測(cè)試 極簡(jiǎn)教程

gomock 是 Google 開(kāi)源的 Golang 測(cè)試框架。

GoMock is a mocking framework for the Go programming language.
https://github.com/golang/mock

快速開(kāi)始

安裝 mockgen

To get the latest released version use:
Go version < 1.16

GO111MODULE=on go get github.com/golang/mock/mockgen@v1.6.0

Go 1.16+

go install github.com/golang/mock/mockgen@v1.6.0

定義好被測(cè)接口

// mockgen -source=./driver/navigator_driver.go -destination ./driver/navigator_driver_mock.go -package driver

type INavigatorDriver interface {
    Query(Ctx context.Context,
        SqlClient *sqlclient.SQLClient,
        sqlKey,
        sql string,
        searchOptions ...*engine.Option,
    ) ([]map[string]interface{}, error)

    BatchGetProductInfoMap(Ctx context.Context,
        SqlClient *sqlclient.SQLClient,
        date string,
        ids []int64,
        entityFields []string,
    ) (map[int64]interface{}, error)

    BatchGetBrandInfoMap(Ctx context.Context,
        SqlClient *sqlclient.SQLClient,
        date string,
        ids []int64,
        entityFields []string,
    ) (map[int64]interface{}, error)
}

type NavigatorDriver struct {
}

使用 mockgen 命令行自動(dòng)生成 gomock代碼

gomock通過(guò)mockgen命令生成包含mock對(duì)象的.go文件,其生成的mock對(duì)象具備mock+stub的強(qiáng)大功能.

mockgen -source=./driver/navigator_driver.go -destination ./driver/navigator_driver_mock.go -package driver

其中, navigator_driver_mock.go 是生成的 mock 代碼.

代碼目錄:


類(lèi)型關(guān)系:

生成的Mock Stub代碼如下:

// Code generated by MockGen. DO NOT EDIT.
// Source: ./driver/navigator_driver.go

// Package driver is a generated GoMock package.
package driver

import (
    context "context"
    reflect "reflect"

    ...
    gomock "github.com/golang/mock/gomock"
)

// MockINavigatorDriver is a mock of INavigatorDriver interface.
type MockINavigatorDriver struct {
    ctrl     *gomock.Controller
    recorder *MockINavigatorDriverMockRecorder
}

// MockINavigatorDriverMockRecorder is the mock recorder for MockINavigatorDriver.
type MockINavigatorDriverMockRecorder struct {
    mock *MockINavigatorDriver
}

// NewMockINavigatorDriver creates a new mock instance.
func NewMockINavigatorDriver(ctrl *gomock.Controller) *MockINavigatorDriver {
    mock := &MockINavigatorDriver{ctrl: ctrl}
    mock.recorder = &MockINavigatorDriverMockRecorder{mock}
    return mock
}

// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockINavigatorDriver) EXPECT() *MockINavigatorDriverMockRecorder {
    return m.recorder
}

// BatchGetBrandInfoList mocks base method.
func (m *MockINavigatorDriver) BatchGetBrandInfoMap(Ctx context.Context, SqlClient *sqlclient.SQLClient, date string, ids []int64, entityFields []string) (map[int64]interface{}, error) {
    m.ctrl.T.Helper()
    ret := m.ctrl.Call(m, "BatchGetBrandInfoMap", Ctx, SqlClient, date, ids, entityFields)
    ret0, _ := ret[0].(map[int64]interface{})
    ret1, _ := ret[1].(error)
    return ret0, ret1
}

// BatchGetBrandInfoList indicates an expected call of BatchGetBrandInfoList.
func (mr *MockINavigatorDriverMockRecorder) BatchGetBrandInfoList(Ctx, SqlClient, date, ids, entityFields interface{}) *gomock.Call {
    mr.mock.ctrl.T.Helper()
    return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BatchGetBrandInfoMap", reflect.TypeOf((*MockINavigatorDriver)(nil).BatchGetBrandInfoMap), Ctx, SqlClient, date, ids, entityFields)
}

// BatchGetProductInfoList mocks base method.
func (m *MockINavigatorDriver) BatchGetProductInfoMap(Ctx context.Context, SqlClient *sqlclient.SQLClient, date string, ids []int64, entityFields []string) (map[int64]interface{}, error) {
    m.ctrl.T.Helper()
    ret := m.ctrl.Call(m, "BatchGetProductInfoMap", Ctx, SqlClient, date, ids, entityFields)
    ret0, _ := ret[0].(map[int64]interface{})
    ret1, _ := ret[1].(error)
    return ret0, ret1
}

// BatchGetProductInfoList indicates an expected call of BatchGetProductInfoList.
func (mr *MockINavigatorDriverMockRecorder) BatchGetProductInfoList(Ctx, SqlClient, date, ids, entityFields interface{}) *gomock.Call {
    mr.mock.ctrl.T.Helper()
    return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BatchGetProductInfoMap", reflect.TypeOf((*MockINavigatorDriver)(nil).BatchGetProductInfoMap), Ctx, SqlClient, date, ids, entityFields)
}

// Query mocks base method.
func (m *MockINavigatorDriver) Query(Ctx context.Context, SqlClient *sqlclient.SQLClient, sqlKey, sql string, searchOptions ...*engine.Option) ([]map[string]interface{}, error) {
    m.ctrl.T.Helper()
    varargs := []interface{}{Ctx, SqlClient, sqlKey, sql}
    for _, a := range searchOptions {
        varargs = append(varargs, a)
    }
    ret := m.ctrl.Call(m, "Query", varargs...)
    ret0, _ := ret[0].([]map[string]interface{})
    ret1, _ := ret[1].(error)
    return ret0, ret1
}

// Query indicates an expected call of Query.
func (mr *MockINavigatorDriverMockRecorder) Query(Ctx, SqlClient, sqlKey, sql interface{}, searchOptions ...interface{}) *gomock.Call {
    mr.mock.ctrl.T.Helper()
    varargs := append([]interface{}{Ctx, SqlClient, sqlKey, sql}, searchOptions...)
    return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Query", reflect.TypeOf((*MockINavigatorDriver)(nil).Query), varargs...)
}

測(cè)試代碼實(shí)例

我們來(lái) Mock 如下代碼中的這個(gè)接口調(diào)用的返回值:

datasourceData, _ := navigatorDriver.Query(u.Ctx, u.Datasource.SqlClient, u.Datasource.SqlKey, navigatorSQL)
func (u *UIComponent) RenderDataTable() ([]map[string]interface{}, error) {
    bu, _ := json.Marshal(u)
    fmt.Println(string(bu))
    endTime := u.DateRangeFilter.EndDate
    dateType := u.DateRangeFilter.DaysType
    // 本周期時(shí)間
    dateStr := indexu.GetDateStr(endTime)

    // 1.fetch 數(shù)據(jù)源
    // 1.1 select 數(shù)據(jù)源字段 select columns
    columnNames := make([]string, 0)
    for _, e := range u.Datasource.Columns {
        columnNames = append(columnNames, e.Name)
    }

    // 1.2 數(shù)據(jù)源表
    datasourceTable := u.Datasource.TableName

    // 1.3 過(guò)濾條件 DateRangeFilter 是固定的
    whereExpr := buildWhereExpr(dateStr, dateType, u)
    datasourceCQL := alpha.NewCQL().SELECT(columnNames...).FROM(datasourceTable).WHERE(whereExpr).ORDERBY2(u.Datasource.DSOrderType, u.Datasource.DSOrderColumn).LIMIT2(u.Datasource.DSLimit)

    // 1.4 從數(shù)據(jù)源獲取數(shù)據(jù)(領(lǐng)航者)
    // TODO MOCK, 線上用真實(shí)的 NavigatorQueryList 查詢
    navigatorDriver := u.INavigatorDriver
    navigatorSQL := datasourceCQL.Compile()
    logu.CtxInfo(u.Ctx, "RenderDataTable", "navigatorSQL: %v", navigatorSQL)
    datasourceData, _ := navigatorDriver.Query(u.Ctx, u.Datasource.SqlClient, u.Datasource.SqlKey, navigatorSQL)
    // 1.5 RSD 數(shù)據(jù)中添加排名字段信息 RankKey
    if u.NeedRank {
        datasourceData = rocket.NewRSD2(datasourceData, u.Ctx, u.Datasource.SqlClient, u.INavigatorDriver).WithRank(u.RankKey, u.Datasource.Columns).Records
    }

    // 2.內(nèi)存指標(biāo)計(jì)算
    sqlite, _ := driver.InitSqlite(u.Ctx, map[string]interface{}{})

    // 2.1 從數(shù)據(jù)源返回?cái)?shù)據(jù)中解析出列的元數(shù)據(jù)信息
    columns := ParseColumnsMeta(datasourceData)
    fmt.Println(columns)

    // 2.2 表名生成
    sqliteTableName := driver.GenerateUniqSQLiteTableName()

    // 2.3 建內(nèi)存表
    driver.CreateTable(u.Ctx, sqliteTableName, columns, sqlite)
    // 2.4 同步數(shù)據(jù)到內(nèi)存
    driver.InsertData(u.Ctx, sqliteTableName, datasourceData, columns, sqlite)

    // 2.5 內(nèi)存數(shù)據(jù)條數(shù)校驗(yàn)
    count, _, _ := driver.Query(nil, fmt.Sprintf("select count(1) as count from %s", sqliteTableName), sqlite)

    if nums, err := convert.ToInt64E(count[0]["count"]); err == nil && nums <= 0 {
        return nil, fmt.Errorf("datasource empty")
    }

    // 2.6 內(nèi)存計(jì)算非指標(biāo)列
    var selectItem = []string{}
    for _, c := range u.Datasource.Columns { // 指標(biāo)計(jì)算規(guī)則元數(shù)據(jù)信息
        if !c.IsDataIndex {
            cname := c.Name
            selectItem = append(selectItem, cname)
        }
    }
    // 2.7 內(nèi)存計(jì)算指標(biāo)列
    indexColumns := getIndexColumns(u.Datasource.Columns)
    // add incr select items
    for _, column := range indexColumns {
        columnName := column.Name
        var exp = fmt.Sprintf("IndexInfo(%s) as %s", columnName, columnName)
        selectItem = append(selectItem, exp)
    }

    // 2.8 CQL中添加排名信息 UDF
    if u.NeedRank {
        // Rank Key 是單獨(dú)指定的,不是數(shù)據(jù)列的概念
        rankKey := u.RankKey
        selectItem = append(selectItem, fmt.Sprintf("RankInfo(%s) as %s", rankKey, rankKey))
    }

    memCQL := alpha.NewCQL().
        SELECT(selectItem...).
        FROM(sqliteTableName)

    if u.DFLimit != nil && u.DFOffset != nil {
        memCQL = memCQL.LIMIT3(*u.DFLimit, *u.DFOffset)
    } else if u.DFLimit != nil && u.DFOffset == nil {
        memCQL = memCQL.LIMIT2(*u.DFLimit)
    }

    incrSQL := memCQL.Compile()
    fmt.Println(incrSQL)

    result, _, _ := driver.Query(u.Ctx, incrSQL, sqlite)

    rsd := rocket.NewRSD2(result, u.Ctx, u.Datasource.SqlClient, u.INavigatorDriver).
        UnmarshalIndexInfo(u.Datasource.Columns).
        UnmarshalRankInfo(u.NeedRank, u.RankKey).
        FillEntityInfoColumn(dateStr, u.Datasource.Columns)

    return rsd.Records, nil
}

接口定義

// mockgen -source=./driver/navigator_driver.go -destination ./driver/navigator_driver_mock.go -package driver

type INavigatorDriver interface {
    Query(Ctx context.Context,
        SqlClient *sqlclient.SQLClient,
        sqlKey,
        sql string,
        searchOptions ...*engine.Option,
    ) ([]map[string]interface{}, error)

    BatchGetProductInfoMap(Ctx context.Context,
        SqlClient *sqlclient.SQLClient,
        date string,
        ids []int64,
        entityFields []string,
    ) (map[int64]interface{}, error)

    BatchGetBrandInfoMap(Ctx context.Context,
        SqlClient *sqlclient.SQLClient,
        date string,
        ids []int64,
        entityFields []string,
    ) (map[int64]interface{}, error)
}

type NavigatorDriver struct {
}

mock 測(cè)試代碼

關(guān)鍵代碼行:

    ctrl := gomock.NewController(t)
    defer ctrl.Finish()

    mockDriver := driver.NewMockINavigatorDriver(ctrl)
    // NavigatorQueryList 期望返回
    mockDriver.
        EXPECT().
        Query(ctx, SqlClient, "compass_strategy_chance_property_product_stats_di", gomock.Any(), gomock.Any()).
        Return(driver.MockNavigatorQueryListProductStats())

完整代碼:


var (
    ctx       = context.Background()
    SqlClient = gomock.Any()
)

func TestDataTableUIComponent(t *testing.T) {
    ctrl := gomock.NewController(t)
    defer ctrl.Finish()

    mockDriver := driver.NewMockINavigatorDriver(ctrl)
    // NavigatorQueryList 期望返回
    mockDriver.
        EXPECT().
        Query(ctx, SqlClient, "compass_strategy_chance_property_product_stats_di", gomock.Any(), gomock.Any()).
        Return(driver.MockNavigatorQueryListProductStats())

    mockDriver.
        EXPECT().
        BatchGetProductInfoList(ctx, SqlClient, gomock.Any(), gomock.Any(), gomock.Any()).
        Return(driver.MockNavigatorQueryListProudctMap())

    //mockDriver.
    //  EXPECT().
    //  BatchGetBrandInfoList(ctx, SqlClient, gomock.Any(), gomock.Any(), gomock.Any()).
    //  Return(driver.MockNavigatorQueryListBrandMap())

    // 初始化數(shù)據(jù)源
    columns := []datasource.Column{
        {Name: "date"},
        {Name: "days_type"},
        {Name: "stats_date"},
        {Name: "cate_id"},
        {Name: "cate_name"},
        {Name: "property_name"},
        {Name: "market_name"},
        {Name: "product_property_value"},
        {Name: "product_id", IsRowKey: true, NeedFillEntityInfo: true, EntityType: datasource.Product, EntityInfoColumnKey: "product_info"},
        {Name: "pay_amt", IsDataIndex: true},
        {Name: "pay_combo_cnt", IsDataIndex: true},
    }

    datasoure := &datasource.DataSource{
        TableName:     "compass_strategy_chance_property_product_stats_di",
        Columns:       columns,
        SqlKey:        "compass_strategy_chance_property_product_stats_di",
        SearchOptions: []*engine.Option{},
        DSOrderColumn: "pay_combo_cnt",
        DSOrderType:   alpha.DESC,
        DSLimit:       50,
    }

    // 創(chuàng)建組件
    UIComponent := NewUIComponent(
        ctx,
        mockDriver,
        DataTable,
        datasoure,
        &DateRangeFilter{
            DaysType:  constu.DateType_LAST_SEVEN_DAYS,
            StartDate: 0,
            EndDate:   1653177600,
        },
        &DimFilter{
            DimCondition: map[string]string{"cate_id": "123",
                "market_name":            "碎花",
                "product_property_value": "長(zhǎng)款裙子",
            },
        },
    )

    // 內(nèi)存分頁(yè)
    PageNo := int64(2)
    PageSize := int64(5)

    dflimit := (PageNo - 1) * PageSize
    dfoffset := PageSize

    UIComponent.DFOrderColumn = "pay_combo_cnt"
    UIComponent.DFOrderType = alpha.DESC
    UIComponent.DFLimit = &dflimit
    UIComponent.DFOffset = &dfoffset
    UIComponent.NeedRank = true
    UIComponent.RankKey = "rank"

    // UIComponent 唯一 Render() 數(shù)據(jù)函數(shù)
    result, _ := UIComponent.Render()

    fmt.Println("size:", len(result))

    fmt.Println("====================================================================================")
    b, _ := json.Marshal(result)
    fmt.Println(string(b))
}

gomock

gomock is a mocking framework for the Go programming language. It
integrates well with Go's built-in testing package, but can be used in other
contexts too.

Installation

Once you have installed Go, install the mockgen tool.

Note: If you have not done so already be sure to add $GOPATH/bin to your
PATH.

To get the latest released version use:

Go version < 1.16

GO111MODULE=on go get github.com/golang/mock/mockgen@v1.6.0

Go 1.16+

go install github.com/golang/mock/mockgen@v1.6.0

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.

Running mockgen

mockgen has two modes of operation: source and reflect.

Source mode

Source mode generates mock interfaces from a source file.
It is enabled by using the -source flag. Other flags that
may be useful in this mode are -imports and -aux_files.

Example:

mockgen -source=foo.go [other options]

Reflect mode

Reflect mode generates mock interfaces by building a program
that uses reflection to understand interfaces. It is enabled
by passing two non-flag arguments: an import path, and a
comma-separated list of symbols.

You can use "." to refer to the current path's package.

Example:

mockgen database/sql/driver Conn,Driver

# Convenient for `go:generate`.
mockgen . Conn,Driver

Flags

The mockgen command is used to generate source code for a mock
class given a Go source file containing interfaces to be mocked.
It supports the following flags:

  • -source: A file containing interfaces to be mocked.

  • -destination: A file to which to write the resulting source code. If you
    don't set this, the code is printed to standard output.

  • -package: The package to use for the resulting mock class
    source code. If you don't set this, the package name is mock_ concatenated
    with the package of the input file.

  • -imports: A list of explicit imports that should be used in the resulting
    source code, specified as a comma-separated list of elements of the form
    foo=bar/baz, where bar/baz is the package being imported and foo is
    the identifier to use for the package in the generated source code.

  • -aux_files: A list of additional files that should be consulted to
    resolve e.g. embedded interfaces defined in a different file. This is
    specified as a comma-separated list of elements of the form
    foo=bar/baz.go, where bar/baz.go is the source file and foo is the
    package name of that file used by the -source file.

  • -build_flags: (reflect mode only) Flags passed verbatim to go build.

  • -mock_names: A list of custom names for generated mocks. This is specified
    as a comma-separated list of elements of the form
    Repository=MockSensorRepository,Endpoint=MockSensorEndpoint, where
    Repository is the interface name and MockSensorRepository is the desired
    mock name (mock factory method and mock recorder will be named after the mock).
    If one of the interfaces has no custom name specified, then default naming
    convention will be used.

  • -self_package: The full package import path for the generated code. The
    purpose of this flag is to prevent import cycles in the generated code by
    trying to include its own package. This can happen if the mock's package is
    set to one of its inputs (usually the main one) and the output is stdio so
    mockgen cannot detect the final output package. Setting this flag will then
    tell mockgen which import to exclude.

  • -copyright_file: Copyright file used to add copyright header to the resulting source code.

  • -debug_parser: Print out parser results only.

  • -exec_only: (reflect mode) If set, execute this reflection program.

  • -prog_only: (reflect mode) Only generate the reflection program; write it to stdout and exit.

  • -write_package_comment: Writes package documentation comment (godoc) if true. (default true)

For an example of the use of mockgen, see the sample/ directory. In simple
cases, you will need only the -source flag.

Building Mocks

type Foo interface {
  Bar(x int) int
}

func SUT(f Foo) {
 // ...
}

func TestFoo(t *testing.T) {
  ctrl := gomock.NewController(t)

  // Assert that Bar() is invoked.
  defer ctrl.Finish()

  m := NewMockFoo(ctrl)

  // Asserts that the first and only call to Bar() is passed 99.
  // Anything else will fail.
  m.
    EXPECT().
    Bar(gomock.Eq(99)).
    Return(101)

  SUT(m)
}

If you are using a Go version of 1.14+, a mockgen version of 1.5.0+, and are
passing a *testing.T into gomock.NewController(t) you no longer need to call
ctrl.Finish() explicitly. It will be called for you automatically from a self
registered Cleanup function.

Building Stubs

type Foo interface {
  Bar(x int) int
}

func SUT(f Foo) {
 // ...
}

func TestFoo(t *testing.T) {
  ctrl := gomock.NewController(t)
  defer ctrl.Finish()

  m := NewMockFoo(ctrl)

  // Does not make any assertions. Executes the anonymous functions and returns
  // its result when Bar is invoked with 99.
  m.
    EXPECT().
    Bar(gomock.Eq(99)).
    DoAndReturn(func(_ int) int {
      time.Sleep(1*time.Second)
      return 101
    }).
    AnyTimes()

  // Does not make any assertions. Returns 103 when Bar is invoked with 101.
  m.
    EXPECT().
    Bar(gomock.Eq(101)).
    Return(103).
    AnyTimes()

  SUT(m)
}

Modifying Failure Messages

When a matcher reports a failure, it prints the received (Got) vs the
expected (Want) value.

Got: [3]
Want: is equal to 2
Expected call at user_test.go:33 doesn't match the argument at index 1.
Got: [0 1 1 2 3]
Want: is equal to 1

Modifying Want

The Want value comes from the matcher's String() method. If the matcher's
default output doesn't meet your needs, then it can be modified as follows:

gomock.WantFormatter(
  gomock.StringerFunc(func() string { return "is equal to fifteen" }),
  gomock.Eq(15),
)

This modifies the gomock.Eq(15) matcher's output for Want: from is equal to 15 to is equal to fifteen.

Modifying Got

The Got value comes from the object's String() method if it is available.
In some cases the output of an object is difficult to read (e.g., []byte) and
it would be helpful for the test to print it differently. The following
modifies how the Got value is formatted:

gomock.GotFormatterAdapter(
  gomock.GotFormatterFunc(func(i interface{}) string {
    // Leading 0s
    return fmt.Sprintf("%02d", i)
  }),
  gomock.Eq(15),
)

If the received value is 3, then it will be printed as 03.

Debugging Errors

reflect vendoring error

cannot find package "."
... github.com/golang/mock/mockgen/model

If you come across this error while using reflect mode and vendoring
dependencies there are three workarounds you can choose from:

  1. Use source mode.
  2. Include an empty import import _ "github.com/golang/mock/mockgen/model".
  3. Add --build_flags=--mod=mod to your mockgen command.

This error is due to changes in default behavior of the go command in more
recent versions. More details can be found in
#494.

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容