简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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