Go 1.11 已終止支援,並將於 2026 年 1 月 31 日
淘汰。淘汰後,您將無法部署 Go 1.11 應用程式,即使貴機構先前使用機構政策重新啟用舊版執行階段的部署作業也一樣。現有的 Go 1.11 應用程式在
淘汰日期過後,仍會繼續執行並接收流量。建議您
遷移至最新支援的 Go 版本。
Go 適用的本機單元測試
透過集合功能整理內容
你可以依據偏好儲存及分類內容。
本機單元測試會在您的環境中執行,不會存取遠端元件。App Engine 提供的測試公用程式採用了 Cloud Datastore 及其他 App Engine 服務的本機實作。
開發服務會在本機模擬真實服務的行為藉以進行測試。例如,編寫 Cloud Datastore 與 Memcache 測試中顯示的資料儲存庫使用量可讓您測試資料儲存庫程式碼,而無須對真實資料儲存庫提出任何要求。在資料儲存庫單元測試期間儲存的任何實體都會在本機儲存,並於測試執行完成後遭到刪除。您可以執行小型、快速的測試,而無須依賴資料儲存庫本身。
這份文件說明如何使用 Go 測試套件,針對本機 App Engine 服務編寫單元測試。
Go 測試套件
您可以使用 goapp
工具自動下載、建構及測試 Go 套件。goapp
是 Go 適用的 App Engine SDK 的一部分。
您可以結合 goapp test
指令和標準 Go testing
套件,對應用程式碼執行單元測試。如需對 Go 進行測試的背景資訊,請參閱「如何編寫 Go 程式碼」的「測試」一節與「測試套件參考資料」。
單元測試包含在結尾帶有 _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
的呼叫會在子程序中啟動 dev_appserver.py
,用於在測試期間處理 API 呼叫。這個子程序會隨著對 done
的呼叫而關閉。
如要進一步控制基礎執行個體,可以改用 aetest.NewInstance
。這可以讓您建立多個相關內容,並建立這些內容與 http.Request
物件的關聯。
詳情請參閱 aetest 套件參考資料。
編寫 Cloud Datastore 與 memcache 測試
使用資料儲存庫或 memcache 測試程式碼是很簡單的,特別是當您使用 aetest
套件建立了 context.Context
時:在測試呼叫 aetest.NewContext
中建立 context,以傳送至測試之下的函式。
SDK 中的 transaction
示範應用程式提供程式碼結構範例,可供測試,並說明如何測試使用資料儲存區的程式碼:
此測試可以使用 goapp test
指令執行:
goapp test ./demos/transaction
memcache 的測試遵循著相同的模式:在測試中設定 memcache 的初始狀態、執行正在進行測試的函式,然後確認函式是否依照期望的方式查詢/修改 memcache。
除非另有註明,否則本頁面中的內容是採用創用 CC 姓名標示 4.0 授權,程式碼範例則為阿帕契 2.0 授權。詳情請參閱《Google Developers 網站政策》。Java 是 Oracle 和/或其關聯企業的註冊商標。
上次更新時間:2025-09-04 (世界標準時間)。
[[["容易理解","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 (世界標準時間)。"],[[["\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."]]