Http Test
Go Unit Test explains how to use test package and test simple json handle functions.
Next target is to test http request and response. (web application)
Steps
This is the step to write test
- Create multiprexor
- Add handler
- Create recorder
- Create request
- Record into recorder
- Check
Example
At first, let’s create simple API (handler)
simplemethodhandler.go
package web import ( "errors" "fmt" "net/http" "path" "strconv" ) func handleRequest(w http.ResponseWriter, r *http.Request) { var err error switch r.Method { case "GET": err = handleGet(w, r) case "POST": err = errors.New("Not Support") case "PUT": err = errors.New("Not Support") case "DELETE": err = errors.New("Not Support") } if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } } func handleGet(w http.ResponseWriter, r *http.Request) (err error) { id, err := strconv.Atoi(path.Base(r.URL.Path)) if err != nil { return } fmt.Println(id) w.Header().Set("Content-Type", "application/json") w.Write([]byte("{\"id\":1}")) return }
This is simple handler
To support only GET request and others are mock.
GET request returns simple json data
Next is test
simplemethodhandler_test.go
Same as last entry, file name is xxxx_test.go
package web import ( "net/http" "net/http/httptest" "os" "testing" ) var mux *http.ServeMux var writer *httptest.ResponseRecorder func TestMain(m *testing.M) { setUp() code := m.Run() os.Exit(code) } func setUp() { // Set up common functions mux = http.NewServeMux() mux.HandleFunc("/get/", handleRequest) writer = httptest.NewRecorder() } func TestHandleGet(t *testing.T) { request, _ := http.NewRequest("GET", "/get/1", nil) mux.ServeHTTP(writer, request) if writer.Code != 200 { t.Errorf("Response code is %v", writer.Code) } }
func TestMain(m *testing.M) is common function for test methods, if there are multiple tests in, this is called at first. We will write common part here.
In this example, prepare mux and recorder
Actual test is under func TestXxxxx.
Create request and call ServeHTTP method, and check response. If response is not 200, create error.
コメント