0
 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?

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83

1 Answers1

0

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")
}
Ganeshdip
  • 389
  • 2
  • 10