1

我正在尝试使用 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

--- 失败:TestGetS (0.00s) mongoManager_test.go:20: 缺少对 *mocks.MockMongoManager.GetS 的调用(等于 cacargroup)/Users/charles/workspace/src/bitbucket.org/tekion/tbaas /mongoManager/mongoManager_test.go:16 mongoManager_test.go:20: 由于缺少调用而中止测试失败退出状态 1

4

1 回答 1

0

您实际上会看到接口中的方法使用错误的返回类型实现。但是您正在使用它,它什么都不返回并链接实现。只需删除GetS.

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)
}
于 2018-02-25T19:31:07.640 回答