Created
June 22, 2016 00:10
-
-
Save cbandy/b727d03d398cdef8917d5b8d451dcb86 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type repo struct { | |
execSQL func(query string, args ...interface{}) (sql.Result, error) | |
queryRow func(query string, args ...interface{}) func(dest ...interface{}) error | |
} | |
func NewRepo(db *sql.DB) repo { | |
return repo{ | |
execSQL: db.Exec, | |
queryRow: func(query string, args ...interface{}) func(...interface{}) error { | |
return db.QueryRow(query, args...).Scan | |
}, | |
} | |
} | |
func (r repo) Add(id, name string) error { | |
_, err := r.execSQL(`INSERT INTO tbl (id, name) VALUES ($1, $2)`, id, name) | |
return err | |
} | |
func (r repo) Read(id string) (string, error) { | |
var name string | |
err := r.queryRow(`SELECT name FROM tbl WHERE id = $1`, id)(&name) | |
return name, err | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func (s *RepoTestSuite) SetupTest() { | |
s.subject = NewRepo(s.db) | |
} | |
func (s *RepoTestSuite) Test_Add_UnexpectedError() { | |
expected := errors.New("bampf") | |
s.subject.execSQL = func(string, ...interface{}) (sql.Result, error) { return nil, expected } | |
err := s.subject.Add(s.id, s.name) | |
s.Equal(expected, err) | |
} | |
func (s *RepoTestSuite) Test_Read_UnexpectedError() { | |
expected := errors.New("boom") | |
s.subject.queryRow = func(string, ...interface{}) func(...interface{}) error { | |
return func(...interface{}) error { return expected } | |
} | |
_, err := s.subject.Read(s.id) | |
s.Equal(expected, err) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment