用于http处理程序测试的Golang模拟函数

时间:2015-03-05 19:07:12

标签: unit-testing go mocking

我正在为PostLoginHandler编写单元测试,需要模拟会话中间件功能。在我的处理程序中,它调用session.Update(),我想模拟它返回nil。

在阅读各种答案后,我的第一直觉是制作一个SessionManager界面,但即便如此,我还不清楚如何继续。

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)
        }
    }
}

1 个答案:

答案 0 :(得分:4)

我建议您使用一对链接:

Testing in Go - Github:此链接说明如何使用mux包进行回复的模拟路由。

示例:

func TestUsersService_Get_specifiedUser(t *testing.T) {
    setup()
    defer teardown()

    mux.HandleFunc("/users/u", 
        func(w http.ResponseWriter, r *http.Request) {
            testMethod(t, r, "GET")
            fmt.Fprint(w, `{"id":1}`)
        }
    )

    user, _, err := client.Users.Get("u")
    if err != nil {
        t.Errorf("Users.Get returned error: %v", err)
    }

    want := &User{ID: Int(1)}
    if !reflect.DeepEqual(user, want) {
       t.Errorf("Users.Get returned %+v, want %+v", 
                user, want)
    }
}  

testflight:一个用于向服务器发出简单http请求的包,使用testflight和mux生成模拟端点,你可以做一个完美的测试。

示例:

func TestPostWithForm(t *testing.T) {
    testflight.WithServer(Handler(), func(r *testflight.Requester) {
        response := r.Post("/post/form", testflight.FORM_ENCODED, "name=Drew")

        assert.Equal(t, 201, response.StatusCode)
        assert.Equal(t, "Drew created", response.Body)
    })
}