簡體   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

}

該連接通常應通過參數注入到 function 中。 如何在不修改代碼的情況下實現單元測試?

使用數據庫相關功能的接口並實現它以使用模擬數據進行測試。請參閱下面的示例代碼 -

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