Skip to content

Instantly share code, notes, and snippets.

@krak3n
Created October 4, 2018 01:48
Show Gist options
  • Save krak3n/65e98dac5aa30da7bd66b09286e93e0f to your computer and use it in GitHub Desktop.
Save krak3n/65e98dac5aa30da7bd66b09286e93e0f to your computer and use it in GitHub Desktop.
type TestSetter struct {
cmd *redis.StatusCmd
}
func (t *TestSetter) Set(k string, v interface{}, d time.Duration) *redis.StatusCmd {
return t.cmd
}
// Unit - make it fail
func Test_setUser(t *testing.T) {
expectedErr := errors.New("some random error")
ts := &TestSetter{
cmd: redis.NewStatusResult("", expectedErr),
}
err := setUser(ts, nil)
if err != expectedErr {
t.Error("unexpected error: %s", err)
}
}
// End to End - connect to a real redis server
func TestSetUser(t *testing.T) {
rc := redis.NewClient(...)
db := &UserDB{rc}
u := &User{...}
err := db.SetUser(u)
if err != nil {
t.Error("unexpected error: %s", err)
}
}
type User struct {
Id string `json:"id"`
Name string `json:"name"`
}
type UserDB struct {
RedisClient *redis.Client
}
func (db *UserDB) SetUser(u *User) error {
return setUser(db.RedisClient, u)
}
type setter interface {
Set(string, interface{}, time.Duration) *redis.StatusCmd
}
func setUser(db setter, u *User) error {
// you probs wanna do some encoding here to bytes or json or whatever
return db.Set(fmt.Sprintf("user.%s", u.Id), u, 0).Err()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment