Mantieni tutto organizzato con le raccolte
Salva e classifica i contenuti in base alle tue preferenze.
Ciò che dovresti testare dipende da fattori quali il tipo di app, il team di sviluppo, la quantità di codice legacy e l'architettura utilizzata. Le seguenti sezioni descrivono gli aspetti che un principiante potrebbe prendere in considerazione quando pianifica gli elementi da testare nella propria app.
Organizzazione delle directory di test
Un progetto tipico in Android Studio contiene due directory che contengono i test, a seconda dell'ambiente di esecuzione. Organizza i test nelle seguenti directory come descritto:
La directory androidTest deve contenere i test eseguiti su dispositivi reali o virtuali. Questi test includono test di integrazione, test end-to-end e altri test in cui la JVM da sola non è in grado di convalidare la funzionalità dell'app.
La directory test deve contenere i test eseguiti sulla macchina locale,
ad esempio i test delle unità. A differenza di quanto sopra, questi possono essere test eseguiti su una JVM locale.
Test delle unità essenziali
Quando segui le best practice, assicurati di utilizzare i test delle unità nei seguenti casi:
Test delle unità per ViewModels, o presentatori.
Test delle unità per il livello dati, in particolare i repository. La maggior parte del livello dati
dovrebbe essere indipendente dalla piattaforma. In questo modo i test possono essere raddoppiati per sostituire i moduli del database
e le origini dati remote nei test. Consulta la guida sull'utilizzo delle doppie prove in Android
Test delle unità per altri livelli indipendenti dalla piattaforma, ad esempio il livello Dominio, come con casi d'uso e interattori.
Test delle unità per classi di utilità come la manipolazione delle stringhe e la matematica.
Test dei casi limite
I test delle unità devono essere incentrati sia sui casi normali che sui casi limite. I casi limite sono scenari rari che è improbabile che i tester umani e i test più grandi vengano rilevati. Ecco alcuni esempi:
Operazioni matematiche che utilizzano numeri negativi, zero e condizioni
di confine.
Tutti i possibili errori di connessione di rete.
Dati danneggiati, ad esempio JSON in formato non corretto.
Simulazione dello spazio di archiviazione completo durante il salvataggio in un file.
Oggetto ricreato nel corso di un processo (ad esempio un'attività quando il dispositivo viene ruotato).
Test delle unità da evitare
Alcuni test delle unità devono essere evitati a causa del loro basso valore:
Test che verificano il corretto funzionamento del framework o di una libreria, non del codice.
I punti di ingresso del framework, come attività, frammenti o servizi, non devono avere una logica di business, pertanto il test delle unità non deve essere una priorità. I test delle unità per le attività hanno poco valore perché coprirebbero principalmente il codice del framework e richiedono una configurazione più complessa. I test strumentali, come i test UI,
possono coprire queste classi.
Test UI
Esistono diversi tipi di test dell'interfaccia utente da utilizzare:
I test dell'interfaccia utente di Screen controllano le interazioni critiche degli utenti in un'unica schermata. Eseguono azioni quali fare clic sui pulsanti, digitare moduli e verificare gli stati visibili. Una lezione di test per schermata è un buon punto di partenza.
Test del flusso utente o Test di navigazione, che coprono i percorsi più comuni. Questi test simulano un utente che si muove attraverso un flusso di navigazione. Sono test semplici, utili per verificare gli arresti anomali in fase di runtime all'inizializzazione.
Altri test
Esistono test più specializzati, come test degli screenshot, test delle prestazioni e test delle scimmie. Puoi anche classificare i test per scopo, ad esempio
regressioni, accessibilità e compatibilità.
Continua a leggere
Per eseguire un test in modo isolato, spesso è necessario sostituire le dipendenze del soggetto sottoposto a test con dipendenze false o fittizie, chiamate "doppi di test" in generale. Continua a leggere in Utilizzare le doppie di prova in Android.
Per scoprire come creare test delle unità e dell'interfaccia utente, consulta i codelab sui test.
I campioni di contenuti e codice in questa pagina sono soggetti alle licenze descritte nella Licenza per i contenuti. Java e OpenJDK sono marchi o marchi registrati di Oracle e/o delle sue società consociate.
Ultimo aggiornamento 2025-07-27 UTC.
[[["Facile da capire","easyToUnderstand","thumb-up"],["Il problema è stato risolto","solvedMyProblem","thumb-up"],["Altra","otherUp","thumb-up"]],[["Mancano le informazioni di cui ho bisogno","missingTheInformationINeed","thumb-down"],["Troppo complicato/troppi passaggi","tooComplicatedTooManySteps","thumb-down"],["Obsoleti","outOfDate","thumb-down"],["Problema di traduzione","translationIssue","thumb-down"],["Problema relativo a esempi/codice","samplesCodeIssue","thumb-down"],["Altra","otherDown","thumb-down"]],["Ultimo aggiornamento 2025-07-27 UTC."],[],[],null,["# What to test in Android\n\nWhat you should test depends on factors such as the type of app, the development\nteam, the amount of legacy code, and the architecture used. The following\nsections outline what a beginner might want to consider when planning what to\ntest in their app.\n\nOrganization of test directories\n--------------------------------\n\nA typical project in Android Studio contains two directories that hold tests\ndepending on their execution environment. Organize your tests in the following\ndirectories as described:\n\n- The `androidTest` directory should contain the tests that run on real or virtual devices. Such tests include integration tests, end-to-end tests, and other tests where the JVM alone cannot validate your app's functionality.\n- The `test`directory should contain the tests that run on your local machine, such as unit tests. In contrast to the above, these can be tests that run on a local JVM.\n\nEssential unit tests\n--------------------\n\nWhen following best practice, you should ensure you use unit tests in the\nfollowing cases:\n\n- **Unit tests** for **ViewModels**, or presenters.\n- **Unit tests** for the **data** layer, especially repositories. Most of the data layer should be platform-independent. Doing so enables test doubles to replace database modules and remote data sources in tests. See the guide on [using test doubles in Android](/training/testing/fundamentals/test-doubles)\n- **Unit tests** for other platform-independent layers such as the **Domain** layer, as with use cases and interactors.\n- **Unit tests** for **utility classes** such as string manipulation and math.\n\n### Testing Edge Cases\n\nUnit tests should focus on both normal and edge cases. Edge cases are uncommon\nscenarios that human testers and larger tests are unlikely to catch. Examples\ninclude the following:\n\n- Math operations using negative numbers, zero, and [boundary\n conditions](https://en.wikipedia.org/wiki/Off-by-one_error).\n- All the possible network connection errors.\n- Corrupted data, such as malformed JSON.\n- Simulating full storage when saving to a file.\n- Object recreated in the middle of a process (such as an activity when the device is rotated).\n\n### Unit Tests to Avoid\n\nSome unit tests should be avoided because of their low value:\n\n- Tests that verify the correct operation of the framework or a library, not your code.\n- Framework entry points such as *activities, fragments, or services* should not have business logic so unit testing shouldn't be a priority. Unit tests for activities have little value, because they would cover mostly framework code and they require a more involved setup. Instrumented tests such as UI tests can cover these classes.\n\nUI tests\n--------\n\nThere are several types of UI tests you should employ:\n\n- **Screen UI tests** check critical user interactions in a single screen. They perform actions such as clicking on buttons, typing in forms, and checking visible states. One test class per screen is a good starting point.\n- **User flow tests** or **Navigation tests**, covering most common paths. These tests simulate a user moving through a navigation flow. They are simple tests, useful for checking for run-time crashes in initialization.\n\n| **Note:** Test coverage is a metric that some testing tools can calculate, and indicates how much of your code is visited by your tests. It can detect untested portions of the codebase, but it should not be used as the only metric to claim a good testing strategy.\n\nOther tests\n-----------\n\nThere are more specialized tests such as screenshot tests, performance tests,\nand [monkey tests](/studio/test/monkey). You can also categorize tests by purpose, such as\nregressions, accessibility, and compatibility.\n\nFurther reading\n---------------\n\nIn order to test in isolation, you oftentimes need to replace the dependencies\nof the subject under test with fake or mock dependencies, called \"Test doubles\"\nin general. Continue reading about them in [Using test doubles in Android](/training/testing/fundamentals/test-doubles).\n\nIf you want to learn how to create unit and UI tests, check out the [Testing\ncodelabs](/codelabs/advanced-android-kotlin-training-testing-basics)."]]