在Go lang中使用模拟编写单元测试

时间:2019-05-17 13:06:27

标签: go mocking

我最近开始学习Golang,并在其中编写了REST API。现在,我想通过隔离不同的组件来对其进行单元测试。

项目结构如下所示,有两个主要软件包

├── main.go
├── routes
│   ├── routes.go
│   └── routes_test.go
├── db
│   └── db.go

main.go :项目的主要入口点

routes / routes.go :HTTP路由处理程序包

db / db.go :数据库处理程序包

现在,当我测试http路由时,我只想测试是否将请求路由到适当的处理函数,然后它们相应地响应。在实际的应用程序中,处理程序函数实际上会插入/更新数据库,但是我不想在测试时这样做。因此,如果我可以模拟数据库对象并使处理程序函数对此进行连接/读取/写入,但是我不确定如何做到这一点。

在测试数据库处理程序包db.go时,我认为我不能对此进行嘲笑,我要么必须建立一个测试数据库,然后针对该数据库进行查询。

这是我文件的外观。

routes / routes.go

    package routes

    import (
        "cfengine-service/db"
        "encoding/json"
        "net/http"
        "strings"

        log "github.com/sirupsen/logrus"

        "github.com/gorilla/mux"
    )

    // Route - struct modal for routes
    type Route struct {
        Name        string
        EndPoint    string
        Methods     []string
        HandlerFunc http.HandlerFunc
    }
    var dbHandler = &db.Mongo{}

    // SetupRouter - returns the mux router
    func SetupRouter() *mux.Router {
        err := dbHandler.Connect()
        if err != nil {
            log.Fatal(err)
        }
        router := mux.NewRouter()
        for _, route := range SetUpRoutes() {
            router.HandleFunc(route.EndPoint, route.HandlerFunc).Methods(route.Methods...)
        }
        return router

    }
    func SetUpRoutes() []Route {
        return []Route{
            {
                "Host config Management",
                "/configs/group",
                []string{"GET", "POST"},
                GroupConfig,
            },
    }

func GroupConfig(w http.ResponseWriter, r *http.Request) {
    reqMethod := r.Method
    if reqMethod == "GET" {
        GetGroupConfig(w, r)
    } else if reqMethod == "POST" {
        NewGroupConfig(w, r)
    }

}

func GetGroupConfig(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    // g := r.URL.Query().Get("groupname")
    g := r.FormValue("groupname")
    if g == "" {
        if data, err := dbHandler.ReadAllGroups(); StatusWriter(w, err) {
            _ = json.NewEncoder(w).Encode(data)
        }
    } else {
        if data, err := dbHandler.ReadOneGroup(g); StatusWriter(w, err) {
            _ = json.NewEncoder(w).Encode(data)
        }
    }

}

// NewGroupConfig - end point for creating new config group
func NewGroupConfig(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("content-type", "application/json")
    var group db.GroupConfig
    err := json.NewDecoder(r.Body).Decode(&group)
    StatusWriter(w, err)

    err = dbHandler.CreateGroupConfig(&group)
    StatusWriter(w, err)
}

db / db.go

    package db

    import (
        "cfengine-service/config"
        "cfengine-service/helpers"
        "context"
        "fmt"
        "time"

        log "github.com/sirupsen/logrus"
        "go.mongodb.org/mongo-driver/bson"
        "go.mongodb.org/mongo-driver/mongo"
        "go.mongodb.org/mongo-driver/mongo/options"
    )

    type HostConfig struct {
        Hostname  string            `bson:"_id" json:"hostname"`
        Type      string            `bson:"type" json:"type"`
        Groups    []string          `bson:"groups" json:"groups"`
        Overrides map[string]string `bson:"overrides" json:"overrides"`
        Excludes  []string          `bson:"excludes" json:"excludes"`
        Data      map[string]string `bson:"data" json:"data"`
    }


    // Mongo collection
    type Mongo struct {
        collection *mongo.Collection
    }

    // Storage is interface for db operations
    type Storage interface {
        Connect() error
        ReadAll() ([]HostConfig, error)
        ReadOne() (*HostConfig, error)
        CreateHostConfig(h *HostConfig) error
        CreateGroupConfig(g *GroupConfig) error
        DeleteHostConfig(h *HostConfig) error
        UpdateHostGrops(h string, g string, opr string) error
        validateGroup(ctx context.Context, val string) error
    }

    func (m *Mongo) Connect() error {
        ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
        defer cancel()
        //client, err := mongo.NewClient(config.Config.MongoURI)
        client, err := mongo.Connect(ctx, options.Client().ApplyURI(config.Config.MongoURI))
        if err != nil {
            return err
        }

        log.Info("Connected to MongoDB.....")
        m.collection = client.Database(config.Config.MongoDbName).Collection(config.Config.MongoCollectionName)
        return nil
    }
func (m *Mongo) CreateGroupConfig(g *GroupConfig) error {
    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()
    data, err := bson.Marshal(g)
    if err != nil {
        log.Error(err.Error())
        return err
    }
    _, err = m.collection.InsertOne(ctx, data)
    if err != nil {
        return err
    }
    return nil
}

func (m *Mongo) ReadOneGroup(g string) (GroupConfig, error) {
    ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
    defer cancel()
    var group GroupConfig
    err := m.collection.FindOne(ctx, bson.M{"_id": g}).Decode(&group)
    if err != nil {
        return GroupConfig{}, err
    }

    return group, nil
}

func (m *Mongo) ReadAllGroups() ([]GroupConfig, error) {
    var configs []GroupConfig
    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()
    cur, err := m.collection.Find(ctx, bson.M{"type": "group"})
    if err != nil {
        return nil, err
    }
    defer cur.Close(ctx)
    for cur.Next(ctx) {
        var record GroupConfig
        if err = cur.Decode(&record); err != nil {
            return nil, err
        }
        configs = append(configs, record)
    }
    return configs, nil
}

因此,使用mockgen包在Storage中为db.go接口生成了模拟,但是我不确定如何开始使用它。这是mock_db.go的外观。

mock_db.go

type MockStorage struct {
    ctrl     *gomock.Controller
    recorder *MockStorageMockRecorder
}

// MockStorageMockRecorder is the mock recorder for MockStorage
type MockStorageMockRecorder struct {
    mock *MockStorage
}

// NewMockStorage creates a new mock instance
func NewMockStorage(ctrl *gomock.Controller) *MockStorage {
    mock := &MockStorage{ctrl: ctrl}
    mock.recorder = &MockStorageMockRecorder{mock}
    return mock
}

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

// Connect mocks base method
func (m *MockStorage) Connect() error {
    m.ctrl.T.Helper()
    ret := m.ctrl.Call(m, "Connect")
    ret0, _ := ret[0].(error)
    return ret0
}

// Connect indicates an expected call of Connect
func (mr *MockStorageMockRecorder) Connect() *gomock.Call {
    mr.mock.ctrl.T.Helper()
    return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Connect", reflect.TypeOf((*MockStorage)(nil).Connect))
}
func (m *MockStorage) CreateGroupConfig(arg0 *db.GroupConfig) error {
    m.ctrl.T.Helper()
    ret := m.ctrl.Call(m, "CreateGroupConfig", arg0)
    ret0, _ := ret[0].(error)
    return ret0
}

// CreateGroupConfig indicates an expected call of CreateGroupConfig
func (mr *MockStorageMockRecorder) CreateGroupConfig(arg0 interface{}) *gomock.Call {
    mr.mock.ctrl.T.Helper()
    return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateGroupConfig", reflect.TypeOf((*MockStorage)(nil).CreateGroupConfig), arg0)
}

所以任何人都可以在这里指导我或给我一些提示以朝着正确的方向前进。

1 个答案:

答案 0 :(得分:0)

测试处理程序时的错误是,您正在SetupRouter函数内创建称为“ Singleton对象”的新对象,因为应在main.go中实例化应用程序所需的所有依赖关系,并且将它们作为需要它们的接口。还定义小型接口-理想的接口大小是1或2种方法。

// Storage is an interface that you already have, this way you can pass your mock object while unit testing, Router should also be an interface.

func SetupRouter(db Storage, router Router) *mux.Router {

        err := db.Connect()
        if err != nil {
            log.Fatal(err)
        }
        //router := mux.NewRouter() - you do not need to do this now
        // then perform whateven actions you want to do with router
}

因此,以上代码段只是一个示例,您可以如何模拟在您的案例数据库中的依赖关系,但是正如@Adrian在评论中所说,如果此代码是生产代码,则需要大量重构。