Go 1.11 ha raggiunto la fine del supporto
e verrà
ritirato
il 31 gennaio 2026. Dopo il ritiro, non potrai eseguire il deployment delle applicazioni Go 1.11, anche se la tua organizzazione ha utilizzato in precedenza un criterio dell'organizzazione per riattivare i deployment dei runtime legacy. Le tue applicazioni Go
1.11 continueranno a essere eseguite e a ricevere traffico dopo la
data di ritiro. Ti
consigliamo di
eseguire la migrazione all'ultima versione supportata di Go.
Test locali delle unità per Go
Mantieni tutto organizzato con le raccolte
Salva e classifica i contenuti in base alle tue preferenze.
I test delle unità locali vengono eseguiti all'interno del tuo ambiente senza accedere a componenti remoti.
App Engine fornisce utilità di test che utilizzano implementazioni locali di Cloud Datastore e altri servizi App Engine.
I servizi di sviluppo simulano il comportamento del servizio reale in locale per
i test. Ad esempio, l'utilizzo di Datastore mostrato in Scrittura di test di Cloud Datastore e Memcache ti consente di testare il codice di Datastore senza effettuare richieste al datastore reale. Qualsiasi entità archiviata durante un test unitario del datastore viene archiviata localmente ed eliminata dopo l'esecuzione del test. Puoi eseguire test piccoli e veloci senza alcuna dipendenza dal
datastore stesso.
Questo documento descrive come scrivere test delle unità per i servizi App Engine locali utilizzando il pacchetto di test Go.
Il pacchetto Go Testing
Puoi automatizzare il download, la creazione e il test dei pacchetti Go utilizzando lo strumento goapp
. goapp
fa parte dell'SDK App Engine per Go.
La combinazione del comando goapp test
e del pacchetto standard Go
testing
può essere utilizzata per eseguire test delle unità sul codice dell'applicazione.
Per informazioni di base sui test con Go, consulta la sezione Test di How to Write
Go Code e il riferimento al pacchetto
testing.
I test unitari sono contenuti in file che terminano con il suffisso _test.go
. Ad esempio, supponiamo che tu voglia testare una funzione denominata composeNewsletter
che restituisce un *mail.Message
. Il seguente file newsletter_test.go
mostra
un semplice test per questa funzione:
Questo test verrà richiamato utilizzando il comando goapp test
dalla directory del pacchetto:
goapp test
Lo strumento goapp
si trova nella directory principale dell'SDK App Engine. Ti
consigliamo di inserire questa directory nella variabile PATH
del sistema per semplificare
l'esecuzione dei test.
Il pacchetto aetest
Molte chiamate di funzioni ai servizi App Engine richiedono un context.Context
come argomento. Il pacchetto appengine/aetest
fornito con l'SDK
ti consente di creare un context.Context
fittizio per eseguire i test utilizzando i
servizi forniti nell'ambiente di sviluppo.
La chiamata a aetest.NewContext
avvierà dev_appserver.py
in un sottoprocesso,
che verrà utilizzato per gestire le chiamate API durante il test. Questo sottoprocesso verrà
arrestato con la chiamata a done
.
Per un maggiore controllo sull'istanza sottostante, puoi utilizzare aetest.NewInstance
. In questo modo puoi creare più contesti e associarli agli oggetti http.Request
.
Per saperne di più, consulta il riferimento al pacchetto aetest.
Scrittura di test di Cloud Datastore e
memcache
Il test del codice che utilizza il datastore o memcache è semplice una volta creato un
context.Context
con il pacchetto aetest
: nella chiamata di test
aetest.NewContext
per creare un contesto da passare alla funzione in fase di test.
L'applicazione demo transaction
nell'SDK contiene un esempio di strutturazione del
codice per consentire la testabilità e di come testare il codice che utilizza il datastore:
Questo test può essere eseguito utilizzando il comando goapp test
:
goapp test ./demos/transaction
I test per memcache seguono lo stesso pattern: configura lo stato iniziale di memcache nel test, esegui la funzione in fase di test e verifica che la funzione abbia eseguito query/modificato memcache nel modo previsto.
Salvo quando diversamente specificato, i contenuti di questa pagina sono concessi in base alla licenza Creative Commons Attribution 4.0, mentre gli esempi di codice sono concessi in base alla licenza Apache 2.0. Per ulteriori dettagli, consulta le norme del sito di Google Developers. Java è un marchio registrato di Oracle e/o delle sue consociate.
Ultimo aggiornamento 2025-09-04 UTC.
[[["Facile da capire","easyToUnderstand","thumb-up"],["Il problema è stato risolto","solvedMyProblem","thumb-up"],["Altra","otherUp","thumb-up"]],[["Difficile da capire","hardToUnderstand","thumb-down"],["Informazioni o codice di esempio errati","incorrectInformationOrSampleCode","thumb-down"],["Mancano le informazioni o gli esempi di cui ho bisogno","missingTheInformationSamplesINeed","thumb-down"],["Problema di traduzione","translationIssue","thumb-down"],["Altra","otherDown","thumb-down"]],["Ultimo aggiornamento 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."]]