简体   繁体   English

如何使用sqlmock来mock db,在function内得到的db连接

[英]How to mock db using sqlmock, the db connection obtained within the function

 func loadDataFromDB() Data{
       db, err := sql.Open("mysql","user:password@tcp(127.0.0.1:3306)/hello")
    if err != nil {
        log.Fatal(err)
    }
    defer db.Close()

    rows, err := db.Query("select id, name from users where id = ?", 1)
    if err != nil {
        log.Fatal(err)
    }
    defer rows.Close()

     // ... Parsing and returning

}

The connection should normally be injected into the function via parameters.该连接通常应通过参数注入到 function 中。 How could I implement a unit test without modifying the code?如何在不修改代码的情况下实现单元测试?

Use interface for DB related functions and implement it for testing with mock data.Please see the sample code below-使用数据库相关功能的接口并实现它以使用模拟数据进行测试。请参阅下面的示例代码 -

package app

import (
    "errors"

    errs "github.com/pkg/errors"
)

type DBSuccess struct {
}

func (d *DBSuccess) SaveGopher(g *Gopher) (string, error) {
    return "successid", nil
}

func (d *DBSuccess) GetGopher(id string) (*Gopher, error) {
    return &Gopher{
        Id:   id,
        Name: "",
    }, nil
}

type DBFailure struct {
}

func (d *DBFailure) SaveGopher(g *Gopher) (string, error) {
    return "", errs.Wrap(errors.New("failure in saving to DB"), "failed in saving Gopher")
}

func (d *DBFailure) GetGopher(id string) (*Gopher, error) {
    return nil, errs.Wrap(errors.New("failure in getting from DB"), "failed in fetching Gopher")
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM