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

}

通常应通过参数将连接注入功能。如何在不修改代码的情况下实施单元测试?

最佳答案

将接口用于数据库相关功能,并将其实现以测试模拟数据。请参见下面的示例代码-

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")
}

关于unit-testing - 如何使用sqlmock模拟数据库,该函数内部获得数据库连接,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/61997296/

10-13 04:57