jeudi 5 mars 2015

Golang mocking functions for http handler tests

I am writing a unit test for my PostLoginHandler and need to mock a session middleware function. In my handler it calls session.Update() that I would like to mock to return nil.


My first instinct after reading various answers was to make a SessionManager interface but even then I am unclear how to proceed.


main.go:



func PostLoginHandler(c web.C, w http.ResponseWriter, r *http.Request) {
r.ParseForm()
user, pass := r.PostFormValue("username"), r.PostFormValue("password")
ctx := context.GetContext(c)

if !authorizeUser(user, pass) {
http.Error(w, "Wrong username or password", http.StatusBadRequest)
return
}

ctx.IsLogin = true
err := session.Update(ctx) \\ mock this function call.
if err != nil {
log.Println(err)
return
}
http.Redirect(w, r, "/admin/", http.StatusFound)
}


main_test:



var loginTests = []struct {
username string
password string
code int
}{
{"admin", "admin", http.StatusFound},
{"", "", http.StatusBadRequest},
{"", "admin", http.StatusBadRequest},
{"admin", "", http.StatusBadRequest},
{"admin", "badpassword", http.StatusBadRequest},
}

func TestPostLoginHandler(t *testing.T) {
// setup()
ctx := &context.Context{IsLogin: false, Data: make(map[string]interface{})}
c := newC()
c.Env["context"] = ctx

for k, test := range loginTests {
v := url.Values{}
v.Set("username", test.username)
v.Set("password", test.password)
r, _ := http.NewRequest("POST", "/login", nil)
r.PostForm = v
resp := httptest.NewRecorder()
m.ServeHTTPC(c, resp, r)

if resp.Code != test.code {
t.Fatalf("TestPostLoginHandler #%v failed. Expected: %v\tReceived: %v", k, test.code, resp.Code)
}
}
}

Aucun commentaire:

Enregistrer un commentaire