LoginSignup
46
44

More than 5 years have passed since last update.

アプリケーションサーバのユニットテストする

Posted at

お気に入りの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をこのオブジェクトで起動して、試験することもできます。

参考情報

46
44
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
46
44