kawabatas技術ブログ

試してみたことを書いていきます

【Go言語のtest】HTTPリクエストのテスト

概要

HTTP モックサーバがほしいなら、標準の httptest パッケージを使えばよいとわかったのでメモ。

コード

GET リクエストを投げる ping 関数

func ping(url string) int {
    client := &http.Client{
        Timeout: 5 * time.Second,
    }
    res, err := client.Get(url)
    if err != nil {
        return 0
    }

    if res.StatusCode != http.StatusOK {
        return 0
    }
    return 1
}

テスト

func TestPing(t *testing.T) {
    mockStatusOK := httptest.NewServer(http.HandlerFunc(
        func(w http.ResponseWriter, r *http.Request) {
            w.WriteHeader(http.StatusOK)
        },
    ))
    defer mockStatusOK.Close()

    mockStatusInternalServerError := httptest.NewServer(http.HandlerFunc(
        func(w http.ResponseWriter, r *http.Request) {
            w.WriteHeader(http.StatusInternalServerError)
        },
    ))
    defer mockStatusInternalServerError.Close()

    mockTimeout := httptest.NewServer(http.HandlerFunc(
        func(w http.ResponseWriter, r *http.Request) {
            time.Sleep(10 * time.Second)
            w.WriteHeader(http.StatusOK)
        },
    ))
    defer mockTimeout.Close()

    var res int

    // 200
    res = ping(mockStatusOK.URL)
    if res != 1 {
        t.Errorf("%d want %d", res, 1)
    }

    // 500
    res = ping(mockStatusInternalServerError.URL)
    if res != 0 {
        t.Errorf("%d want %d", res, 0)
    }

    // timeout
    res = ping(mockTimeout.URL)
    if res != 0 {
        t.Errorf("%d want %d", res, 0)
    }
}

httptest パッケージで任意のレスポンスを返すように設定し、

その URL に ping 関数を実行する感じ