gomock, Go,芒果包,MongoMock

gomock, Go,mango package ,MongoMock

我正在尝试使用 gomock 模拟以下方法

func GetS(tenantName string) (*mgo.Session, error) {
    ctx := apiContext.TContext{}
    url, err := connectionURLList.get(tenantName)
    if err != nil {
        log.GenericWarning(ctx,
            fmt.Sprintf("connection to %s not yet created, creating one: %v", tenantName, err), nil)
        if err := connectMongo(tenantName); err == nil {
            return GetS(tenantName) //singleton recursion to again call GetS
        }
        return nil, err
    }
    // ignoring error, expected we will always setting session in session map
    session, _ := connectionList.get(url)
    return session.Copy(), err
}

我的界面

type MongoManager interface {
    GetS(tenantName string) 
}

func TestGetS(t *testing.T) {
    //var mgoCall *mgo.Session
    mockCtrl := gomock.NewController(t)
    defer mockCtrl.Finish()
    mockManagerObj := mocks.NewMockMongoManager(mockCtrl)
    mockManagerObj.EXPECT().GetS("cacargroup").Return(nil)
}

我收到以下错误。有人可以帮忙

 $ go test

--- FAIL: TestGetS (0.00s) mongoManager_test.go:20: missing call(s) to *mocks.MockMongoManager.GetS(is equal to cacargroup) /Users/charles/workspace/src/bitbucket.org/tekion/tbaas/mongoManager/mongoManager_test.go:16 mongoManager_test.go:20: aborting test due to missing call(s) FAIL exit status 1

你实际上看到你的接口中的方法实现了 return 类型的错误。但是您正在使用 return 什么都没有,并且链接了实现。只需删除 GetS 的 return 类型。

type fn func(string) (*mgo.Session, error)

type MongoManager interface {
    NewFunction(GetS, "cascade")
}

func TestGetS(t *testing.T) {
    //var mgoCall *mgo.Session
    mockCtrl := gomock.NewController(t)
    defer mockCtrl.Finish()
    mockManagerObj := mocks.NewMockMongoManager(mockCtrl)
    mockManagerObj.EXPECT().GetS("cacargroup").Return(nil)
}

你也必须从 GetS 函数中删除它

func NewFunction(GetS fn, value string){
   GetS("cascade")
}

func GetS(tenantName string) (*mgo.Session, error){
    ctx := apiContext.TContext{}
    url, err := connectionURLList.get(tenantName)
    if err != nil {
        log.GenericWarning(ctx,
            fmt.Sprintf("connection to %s not yet created, creating one: %v", tenantName, err), nil)
        if err := connectMongo(tenantName); err == nil {
            return GetS(tenantName) //singleton recursion to again call GetS
        }
        return nil, err
    }
    // ignoring error, expected we will always setting session in session map
    session, _ := connectionList.get(url)
}