Golang “Mocking” a Function for Unit Testing

Credits to Tamara Gak (https://unsplash.com/photos/1vZAezBEADw)
type Person struct { ID       int    `db:"id" json:"id"` Name     string `db:"name" json:"name"` BornDate string `db:"born_date" json:"born_date"`}type Address struct { ID         int    `db:"id" json:"id"` UserID     int    `db:"user_id" json:"user_id"` Street     string `db:"street" json:"street"` PostalCode string `db:"postal_code" json:"postal_code"`}type UserProfile struct { User    Person  `json:"person"` Address Address `json:"address"`}func GetPersonByID(id int) (*Person, error) { var user Person err := db.Get(&user, `SELECT id, name, born_date FROM users WHERE id = ?`, id) if err != nil {  return nil, err } return &user, err}func GetPersonAddrByUserID(userID int) (*Address, error) { var addr Address err := db.Get(&addr, `SELECT id, user_id, street, postal_code FROM address WHERE user_id = ?`, userID) if err != nil {  return nil, err } return &addr, err}func GetUserProfile(userID int) (UserProfile, error) { var userProfile UserProfile p, err := GetPersonByID(userID) if err != nil {  return userProfile, err } a, err := GetPersonAddrByUserID(userID) if err != nil {  return userProfile, err } userProfile.User = *p userProfile.Address = *a return userProfile, nil}func JSONMarshalUserProfile(up UserProfile) ([]byte, error) { return json.Marshal(up)}
var GetPersonByID = func(id int) (*Person, error) {
var user Person
.... // function content
}
var GetPersonAddrByUserID = func(userID int) (*Address, error) {
var addr Address
... // function content
}
GetPersonByID = func(id int) (*Person, error) {
// PUT DIFFERENT IMPLEMENTATION HERE
}
func JSONMarshalUserProfile(up UserProfile) ([]byte, error) {  return json.Marshal(up)}
var marshalJSON = json.Marshal
func JSONMarshalUserProfile(up UserProfile) ([]byte, error) { return marshalJSON(up)}
marshalJSON = func(v interface{}) ([]byte, error) {     // Put your mocking / testing implementation here
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store