Go 1.11 はサポートが終了しており、2026 年 1 月 31 日に
非推奨になります。非推奨になると、過去に組織のポリシーを使用して以前のランタイムのデプロイを再度有効にしていた場合でも、Go 1.11 アプリケーションをデプロイできなくなります。既存の Go 1.11 アプリケーションは、
非推奨日以降も引き続き実行され、トラフィックを受信します。
サポートされている最新バージョンの Go に移行することをおすすめします。
ローカルでの Go の単体テスト
コレクションでコンテンツを整理
必要に応じて、コンテンツの保存と分類を行います。
ローカル単体テストは、リモート コンポーネントにアクセスしない環境内で実行します。App Engine には、Cloud Datastore や他の App Engine サービスのローカル実装を使用するテスト ユーティリティが用意されています。
開発サービスは、実際のサービスの動作をテスト目的でローカルにシミュレートします。たとえば、Cloud Datastore と Memcache のテストを作成するで示されているデータストアの使用方法では、実際のデータベースに一切リクエストを行うことなく、データストア コードをテストできます。データストアの単体テストで生成されるエンティティはローカルに格納され、テストの実行後に削除されます。データストア自体に依存することはないため、簡単なテストをすばやく実行できます。
このドキュメントでは、Go の testing パッケージを使用して、ローカルの App Engine サービスに対する単体テストを作成する方法を説明します。
Go の testing パッケージ
Go パッケージのダウンロード、ビルド、テストは、goapp
ツールを使用して自動化できます。goapp
は、App Engine SDK for Go の一部です。
goapp test
コマンドと標準の Go testing
パッケージの組み合わせを使用して、アプリケーション コードに対して単体テストを実行できます。Go でのテストの背景情報については、How to Write Go Code の「Testing」セクションと Package testing リファレンスをご覧ください。
単体テストは、_test.go
という接尾辞で終わるファイルに保存されています。たとえば、composeNewsletter
という名前の関数のテストを行うとします。この関数は、*mail.Message
を返します。次の newsletter_test.go
ファイルは、この関数の簡単なテストを示しています。
このテストは、パッケージのディレクトリ内から goapp test
コマンドを使用して起動します。
goapp test
goapp
ツールは App Engine SDK のルート ディレクトリにあります。テストを簡単に実行できるように、このディレクトリをシステムの PATH
変数に配置することをおすすめします。
aetest
パッケージ
App Engine サービスに対する多くの関数呼び出しでは、引数として context.Context
が必要です。SDK で提供される appengine/aetest
パッケージを使用すると、開発環境で提供されるサービスを使用してテストを実行するための偽の context.Context
を作成できます。
aetest.NewContext
の呼び出しにより、テスト中に API 呼び出しを処理するために使用されるサブプロセスで、dev_appserver.py
が開始されます。このサブプロセスは、done
への呼び出しでシャットダウンします。
基になるインスタンスをより細かく制御するには、代わりに aetest.NewInstance
を使用します。これにより、複数のコンテキストを作成し、それらを http.Request
オブジェクトに関連付けることができます。
詳細については、aetest パッケージ リファレンスをご覧ください。
Cloud Datastore と Memcache のテストを作成する
データストアまたは memcache を使用するコードのテストは、aetest
パッケージで context.Context
を作成したら簡単です。テストで aetest.NewContext
を呼び出し、テスト対象の関数に渡すコンテキストを作成します。
SDK の transaction
デモ アプリケーションには、テストを可能にするコードの構成例と、データストアを使用するコードのテスト方法が含まれています。
このテストは、goapp test
コマンドを使用して実施できます。
goapp test ./demos/transaction
Memcache のテストも同様のパターンに従って実行します。テストで Memcache の初期状態を設定し、テスト対象の関数を実行して、関数によって予期したとおりに Memcache がクエリまたは変更されていることを確認します。
特に記載のない限り、このページのコンテンツはクリエイティブ・コモンズの表示 4.0 ライセンスにより使用許諾されます。コードサンプルは Apache 2.0 ライセンスにより使用許諾されます。詳しくは、Google Developers サイトのポリシーをご覧ください。Java は Oracle および関連会社の登録商標です。
最終更新日 2025-09-04 UTC。
[[["わかりやすい","easyToUnderstand","thumb-up"],["問題の解決に役立った","solvedMyProblem","thumb-up"],["その他","otherUp","thumb-up"]],[["わかりにくい","hardToUnderstand","thumb-down"],["情報またはサンプルコードが不正確","incorrectInformationOrSampleCode","thumb-down"],["必要な情報 / サンプルがない","missingTheInformationSamplesINeed","thumb-down"],["翻訳に関する問題","translationIssue","thumb-down"],["その他","otherDown","thumb-down"]],["最終更新日 2025-09-04 UTC。"],[[["\u003cp\u003eLocal unit tests can be run within your environment without the need to access remote components, using local implementations of App Engine services like Cloud Datastore.\u003c/p\u003e\n"],["\u003cp\u003eThe \u003ccode\u003egoapp test\u003c/code\u003e command, in combination with the standard Go \u003ccode\u003etesting\u003c/code\u003e package, facilitates running unit tests against your application code, which are contained in files ending with the suffix \u003ccode\u003e_test.go\u003c/code\u003e.\u003c/p\u003e\n"],["\u003cp\u003eThe \u003ccode\u003eaetest\u003c/code\u003e package within the App Engine SDK enables the creation of a fake \u003ccode\u003econtext.Context\u003c/code\u003e for testing code that interacts with App Engine services in the development environment.\u003c/p\u003e\n"],["\u003cp\u003eTesting code that utilizes the datastore or memcache is streamlined by creating a \u003ccode\u003econtext.Context\u003c/code\u003e using \u003ccode\u003eaetest.NewContext\u003c/code\u003e within the test, allowing you to pass it to the function being tested.\u003c/p\u003e\n"],["\u003cp\u003e\u003ccode\u003eaetest.NewInstance\u003c/code\u003e provides more control over the underlying test instance, enabling the creation of multiple contexts and their association with \u003ccode\u003ehttp.Request\u003c/code\u003e objects.\u003c/p\u003e\n"]]],[],null,["# Local Unit Testing for Go\n\nLocal unit tests run inside your environment without accessing remote components.\nApp Engine provides testing utilities that use local implementations of Cloud\nDatastore and other [App Engine services](/appengine/docs/legacy/standard/go111/apis).\n\nThe development services simulate the behaviour of the real service locally for\ntesting. For example, the datastore usage shown in [Writing Cloud Datastore\nand Memcache Tests](#Go_Writing_Datastore_and_memcache_tests) allows you to test\nyour datastore code without making any requests to the real datastore. Any\nentity stored during a datastore unit test is stored locally and is deleted\nafter the test run. You can run small, fast tests without any dependency on the\ndatastore itself.\n\nThis document describes how to write unit tests against local App Engine\nservices using the Go testing package.\n\nThe Go Testing package\n----------------------\n\nYou can automate the downloading, building, and testing of Go packages by using\nthe `goapp` tool. `goapp` is part of the\n[App Engine SDK for Go](/appengine/docs/legacy/standard/go111/download#appengine_sdk).\n\nThe combination of the `goapp test` command and the standard Go\n`testing` package can be used to run unit tests against your application code.\nFor a background on testing with Go, see the Testing section of [How to Write\nGo Code](http://golang.org/doc/code.html#Testing) and the [testing package\nreference](http://golang.org/pkg/testing/).\n\nUnit tests are contained in files ending with the suffix `_test.go`. For\nexample, suppose you want to test a function named `composeNewsletter` which\nreturns a `*mail.Message`. The following `newsletter_test.go` file shows\na simple test for that function: \n\n package newsletter\n\n import (\n \t\"reflect\"\n \t\"testing\"\n\n \t\"google.golang.org/appengine/mail\"\n )\n\n func TestComposeNewsletter(t *testing.T) {\n \twant := &mail.https://cloud.google.com/appengine/docs/legacy/standard/go111/reference/latest/mail.html#google_golang_org_appengine_mail_Message{\n \t\tSender: \"newsletter@appspot.com\",\n \t\tTo: []string{\"User \u003cuser@example.com\u003e\"},\n \t\tSubject: \"Weekly App Engine Update\",\n \t\tBody: \"Don't forget to test your code!\",\n \t}\n \tif msg := composeNewsletter(); !reflect.DeepEqual(msg, want) {\n \t\tt.Errorf(\"composeMessage() = %+v, want %+v\", msg, want)\n \t}\n }\n\nThis test would be invoked using the `goapp test` command from within the\npackage's directory: \n\n```\ngoapp test\n```\n\nThe `goapp` tool is found in the root directory of the App Engine SDK. We\nrecommend putting this directory in your system's `PATH` variable to make\nrunning tests simpler.\n\nThe `aetest` package\n--------------------\n\nMany function calls to App Engine services require a `context.Context`\nas an argument. The `appengine/aetest` package provided with the SDK\nallows you to create a fake `context.Context` to run your tests using the\nservices provided in the development environment. \n\n import (\n \t\"testing\"\n\n \t\"google.golang.org/appengine/aetest\"\n )\n\n func TestWithContext(t *testing.T) {\n \tctx, done, err := aetest.https://cloud.google.com/appengine/docs/legacy/standard/go111/reference/latest/aetest.html#google_golang_org_appengine_aetest_NewContext()\n \tif err != nil {\n \t\tt.Fatal(err)\n \t}\n \tdefer done()\n\n \t// Run code and tests requiring the context.Context using ctx.\n \t// ...\n }\n\nThe call to `aetest.NewContext` will start `dev_appserver.py` in a subprocess,\nwhich will be used to service API calls during the test. This subprocess will be\nshutdown with the call to `done`.\n\nFor more control over the underlying instance, you can use `aetest.NewInstance`\ninstead. This gives you the ability to create multiple contexts, and to\nassociate those with `http.Request` objects. \n\n import (\n \t\"errors\"\n \t\"testing\"\n\n \t\"golang.org/x/net/context\"\n\n \t\"google.golang.org/appengine\"\n \t\"google.golang.org/appengine/aetest\"\n \t\"google.golang.org/appengine/datastore\"\n )\n\n func TestMyFunction(t *testing.T) {\n \tinst, err := aetest.NewInstance(nil)\n \tif err != nil {\n \t\tt.Fatalf(\"Failed to create instance: %v\", err)\n \t}\n \tdefer inst.Close()\n\n \treq1, err := inst.NewRequest(\"GET\", \"/gophers\", nil)\n \tif err != nil {\n \t\tt.Fatalf(\"Failed to create req1: %v\", err)\n \t}\n \tc1 := appengine.NewContext(req1)\n\n \treq2, err := inst.NewRequest(\"GET\", \"/herons\", nil)\n \tif err != nil {\n \t\tt.Fatalf(\"Failed to create req2: %v\", err)\n \t}\n \tc2 := appengine.NewContext(req2)\n\n \t// Run code and tests with *http.Request req1 and req2,\n \t// and context.Context c1 and c2.\n \t// ...\n }\n\nRead the [aetest package\nreference](/appengine/docs/legacy/standard/go111/tools/localunittesting/reference)\nfor more information.\n\nWriting Cloud Datastore and\nmemcache tests\n------------------------------------------\n\nTesting code which uses the datastore or memcache is simple once you create a\n`context.Context` with the `aetest` package: in your test call\n`aetest.NewContext` to create a context to pass to the function under test.\n\nThe `transaction` demo application in the SDK has an example of structuring the\ncode to allow testability, and how to test code which uses the datastore: \n\n func TestWithdrawLowBal(t *testing.T) {\n \tctx, done, err := aetest.NewContext()\n \tif err != nil {\n \t\tt.Fatal(err)\n \t}\n \tdefer done()\n \tkey := datastore.NewKey(ctx, \"BankAccount\", \"\", 1, nil)\n \tif _, err := datastore.Put(ctx, key, &BankAccount{100}); err != nil {\n \t\tt.Fatal(err)\n \t}\n\n \terr = withdraw(ctx, \"myid\", 128, 0)\n \tif err == nil || err.Error() != \"insufficient funds\" {\n \t\tt.Errorf(\"Error: %v; want insufficient funds error\", err)\n \t}\n\n \tb := BankAccount{}\n \tif err := datastore.Get(ctx, key, &b); err != nil {\n \t\tt.Fatal(err)\n \t}\n \tif bal, want := b.Balance, 100; bal != want {\n \t\tt.Errorf(\"Balance %d, want %d\", bal, want)\n \t}\n }\n\nThis test can be run using the `goapp test` command: \n\n```\ngoapp test ./demos/transaction\n```\n\nTests for memcache follow the same pattern: set up the initial state of the\nmemcache in your test, run the function being tested, and verify the function\nhas queried/modified the memcache in the way you expect."]]