gpt4 book ai didi

unit-testing - 如何使用sqlmock mock db,函数内获取的db连接

转载 作者:行者123 更新时间:2023-12-01 22:22:41 25 4
gpt4 key购买 nike

 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

}

连接通常应该通过参数注入(inject)到函数中。如何在不修改代码的情况下实现单元测试?

最佳答案

使用数据库相关功能的接口(interface)并实现它以使用模拟数据进行测试。请参阅下面的示例代码 -

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 mock db,函数内获取的db连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61997296/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com