Skip to content

Instantly share code, notes, and snippets.

@jsoriano
Created April 9, 2015 22:24
Show Gist options
  • Save jsoriano/ba32a23dd03c1aa6c0bc to your computer and use it in GitHub Desktop.
Save jsoriano/ba32a23dd03c1aa6c0bc to your computer and use it in GitHub Desktop.
Testing a simple go-martini application with mocks
package mditest
import (
"fmt"
"net/http"
"github.com/go-martini/martini"
redis "gopkg.in/redis.v2"
)
type DataStore interface {
Get(k string) string
Set(k, v string)
}
type RedisDataStore struct {
client *redis.Client
}
func NewRedisDataStore(host string, port int) *RedisDataStore {
fmt.Printf("%v:%v\n", host, port)
d := &RedisDataStore{
client: redis.NewTCPClient(&redis.Options{
Addr: fmt.Sprintf("%v:%v", host, port),
DB: 0,
}),
}
return d
}
func (d *RedisDataStore) Get(k string) string {
command := d.client.Get(k)
if command.Err() != nil {
fmt.Println(command.Err())
return ""
}
return command.Val()
}
func (d *RedisDataStore) Set(k, v string) {
if err := d.client.Set(k, v).Err(); err != nil {
fmt.Println(err)
}
}
type MyInstance struct {
*martini.Martini
}
func NewAppInstance(d DataStore) *MyInstance {
instance := &MyInstance{
martini.New(),
}
router := martini.NewRouter()
router.Get("/get/:id", func(params martini.Params, d DataStore) string {
return d.Get(params["id"])
})
router.Post("/set/:id", func(params martini.Params, r *http.Request, d DataStore) string {
d.Set(params["id"], r.FormValue("value"))
return "OK"
})
instance.Use(martini.Recovery())
instance.Use(martini.Logger())
instance.MapTo(d, (*DataStore)(nil))
instance.Action(router.Handle)
return instance
}
func main() {
d := NewRedisDataStore("127.0.0.1", 6379)
NewAppInstance(d).Run()
}
package mditest
import (
"bytes"
"net/http"
"net/http/httptest"
"net/url"
"strconv"
"testing"
"github.com/stretchr/testify/mock"
)
type MockedDataStore struct {
mock.Mock
}
func (m *MockedDataStore) Get(k string) string {
args := m.Called(k)
return args.String(0)
}
func (m *MockedDataStore) Set(k, v string) {
m.Called(k, v)
}
func TestDatastoreApi(t *testing.T) {
d := new(MockedDataStore)
instance := NewAppInstance(d)
d.On("Set", "foo", "42").Return().Once()
data := url.Values{}
data.Set("value", "42")
request, _ := http.NewRequest("POST", "/set/foo", bytes.NewBufferString(data.Encode()))
request.Header.Add("Content-Type", "application/x-www-form-urlencoded")
request.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))
response := httptest.NewRecorder()
instance.ServeHTTP(response, request)
d.On("Get", "foo").Return("42").Once()
request, _ = http.NewRequest("GET", "/get/foo", nil)
response = httptest.NewRecorder()
instance.ServeHTTP(response, request)
d.AssertExpectations(t)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment