简体   繁体   中英

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

I recommend you a pair of links:

Testing in Go - Github : This link explain how do a mock route with a response using mux package.

Example:

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 : A package for make simple http request to a server, using testflight and mux for make mock endpoints you will can do a perfect test.

Example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM