LoginSignup
9
7

More than 5 years have passed since last update.

GAE/Go で HTTP Handler のテストを書く

Posted at

はじめに

  • GAE/Go 環境の JWT 認証をするアプリケーションで HTTP Handler のテストを書いてみた

通常の httptest との違い

  • 気をつけるのは2点だけで後は普通の httptest みたいなのりでかける

リクエストは google.golang.org/appengine/aetest パッケージを使って作成する

  • リクエストの作成から実行までは以下の流れになる
  • リクエストから生成したコンテキストを使って Datastore へのアクセスなどが行える
    // aetest (App Engine Test) のインスタンス作成
  // テスト用の環境が用意される
    opt := aetest.Options{StronglyConsistentDatastore: true}
    instance, err := aetest.NewInstance(&opt)
    if err != nil {
        t.Fatalf("Failed to create aetest instance: %v", err)
    }
    defer instance.Close()

    // aetest インスタンスからリクエストの作成
    req, _ := instance.NewRequest("POST", "/registration", strings.NewReader(`{"username":"user1", "password":"pass1"}`))
    req.Header.Set("Content-Type", "application/json")

    // レスポンスの作成
    res := httptest.NewRecorder()

    // コンテキストの取得
    ctx := appengine.NewContext(req)

    // リクエストの実行
    RegistrationHandler(res, req)

テストの実行は goapp test を使う

# handler ディレクトリ以下のテストを実行する場合
goapp test ./handler

全文

参考ページ

9
7
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
9
7