Test goji with net / httptest

goji to now trying to write a Web app. When I use it as an API server, I am concerned about testing.

golang the net/http/httptest >` _ packages that do that the test of http comes with from the beginning. Using this makes it easy to write tests.

Httptest.Server creates a server with local loopback interface.

(2014/11/20 postscript) : Because from mopemope's "better to put the Routing test of the good that is has" received a pointed out that, divide the Route set to a different function, we have to use from the test.

Sample application

/hello/hoge return JSON If you come have access to the URL, a simple A pre-called.

package main

import (
    "encoding/json"
    "fmt"
    "net/http"

    "github.com/zenazn/goji"
    "github.com/zenazn/goji/web"
)

type User struct {
    Id   int64
    Name string
}

func hello(c web.C, w http.ResponseWriter, r *http.Request) {
    u := User{
        Id:   1,
        Name: c.URLParams["name"],
    }

    j, _ := json.Marshal(u)
    fmt.Fprintf(w, string(j))
}

func Route(m *web.Mux) {
    m.Get("/hello/:name", hello)
}

func main() {
    Route(goji.DefaultMux)
    goji.Serve()
}

The test for this is as follows.

package main

import (
    "io/ioutil"
    "net/http"
    "net/http/httptest"
    "testing"

    "github.com/zenazn/goji/web"
)

func ParseResponse(res *http.Response) (string, int) {
    defer res.Body.Close()
    contents, err := ioutil.ReadAll(res.Body)
    if err != nil {
        panic(err)
    }
    return string(contents), res.StatusCode
}

func Test_Hello(t *testing.T) {
    m := web.New()
    Route(m)
    ts := httptest.NewServer(m)
    defer ts.Close()

    res, err := http.Get(ts.URL + "/hello/hoge")
    if err != nil {
        t.Error("unexpected")
    }
    c, s := ParseResponse(res)
    if s != http.StatusOK {
        t.Error("invalid status code")
    }
    if c != `{"Id":1,"Name":"hoge"}` {
        t.Error("invalid response")
    }
}

web.New() Create a goji / web of HTTP multiplexer in. After that, if you give it as httptest.NewServer (m), the test server will start up. Do not forget to close with defer.

It is to be noted that the ts.URL, URL contains the port of launched test server is http://127.0.0.1:51923 contains in like a feeling.

For simplicity we make a function called ParseResponse, but this is not required.

Please tell me if there are other ways better.