お気に入りのThinkPadキーボードが壊れて不服な気持ちのうみさまです。
新しいX1Carbonを見てThinkPadへの忠誠心も切れかかっていた所だったので、今度はHHKBでも買います。
さて、golangにはアプリケーションサーバをユニットテストするため、net/http/httptestというパッケージが用意されています。
ハンドラのユニットテスト
例えば、こんな感じのアプリケーションがあったとしてHander()を試験したい場合、
handler.go
package main
import (
"net/http"
"fmt"
)
func Handler( w http.ResponseWriter, r *http.Request ) {
fmt.Fprintf(w, "hello world")
}
func main() {
http.HandleFunc("/", Handler)
http.ListenAndServe(":8080", nil)
}
こんな感じでhttptest.NewServer()を用いてHandler()を単独起動し、試験できます。
handler_test.go
package main
import (
"testing"
"net/http"
"net/http/httptest"
)
func TestHandler(t *testing.T) {
ts := httptest.NewServer( http.HandlerFunc( Handler ) )
defer ts.Close()
res, err := http.Get( ts.URL )
if err != nil {
t.Error("unexpected")
return
}
if res.StatusCode != 200 {
t.Error("Status code error")
return
}
}
ちなみに
クライアントアプリでは、サービスのMockをこのオブジェクトで起動して、試験することもできます。