Mantieni tutto organizzato con le raccolte
Salva e classifica i contenuti in base alle tue preferenze.
Testare le interazioni degli utenti contribuisce ad assicurarti che non riscontrino risultati inaspettati o che non abbiano un'esperienza negativa quando interagiscono con la tua app. Ti consigliamo di acquisire l'abitudine di creare test dell'interfaccia utente (UI) se devi verificare che l'UI della tua app funzioni correttamente.
Un approccio ai test dell'interfaccia utente è quello di chiedere a un tester umano di eseguire una serie di operazioni dell'utente sull'app di destinazione e di verificare che funzioni correttamente. Tuttavia, questo approccio manuale può richiedere molto tempo e essere soggetto a errori. Un approccio più efficiente è scrivere i test dell'interfaccia utente in modo che le azioni utente vengano eseguite in modo automatico. L'approccio automatico ti consente di eseguire i test in modo rapido e affidabile in modo ripetibile.
I test dell'interfaccia utente avviano un'app (o parte di essa), simulano le interazioni degli utenti e infine controllano che l'app abbia reagito in modo appropriato. Si tratta di test di integrazione
che possono variare dalla verifica del comportamento di un piccolo componente a un grande
test di navigazione che attraversa un intero flusso utente. Sono utili per verificare la presenza di regressioni e per verificare la compatibilità con diversi livelli API e dispositivi fisici.
Esegui test dell'interfaccia utente
Per eseguire test UI strumentati utilizzando Android Studio, implementa il codice di test in una cartella di test Android separata (src/androidTest/java). Il
plug-in Android Gradle crea un'app di test in base al codice di test, quindi carica l'app di test sullo stesso dispositivo dell'app di destinazione. Nel codice di test,
puoi utilizzare framework di test dell'interfaccia utente per simulare le interazioni degli utenti nell'app di destinazione, in modo da eseguire attività di test che coprono scenari di utilizzo specifici.
Puoi anche utilizzare Robolectric per eseguire test dell'interfaccia utente sulla JVM.
Architettura e configurazione dei test
L'architettura dell'app deve consentire ai test di sostituire parti dell'app per i doppi di test e devi utilizzare librerie che forniscono utilità per supportare il test. Ad esempio, puoi sostituire un modulo del repository di dati con una versione in memoria che fornisca al test dati deterministici falsi.
Figura 3: test di un'interfaccia utente sostituendo le relative dipendenze con elementi falsi.
L'approccio consigliato per sostituire le dipendenze è l'inserimento di dipendenze. Puoi creare il tuo sistema manualmente, ma ti consigliamo di utilizzare un framework DI come Hilt.
Perché testare automaticamente le UI?
Un'app per Android può avere come target migliaia di dispositivi diversi con molti livelli API e fattori di forma e l'alto livello di personalizzazione offerto dall'OS all'utente significa che la tua app potrebbe essere visualizzata in modo errato o addirittura arrestarsi in modo anomalo su alcuni dispositivi.
I test dell'interfaccia utente ti consentono di eseguire test di compatibilità, verificando il comportamento di un'app in diversi contesti. Ti consigliamo di eseguire i test dell'interfaccia utente su dispositivi diversi
nei seguenti modi:
Livello API: 21, 25 e 30.
Impostazioni internazionali: inglese, arabo e cinese.
Orientamento: verticale, orizzontale.
Inoltre, le app devono controllare il comportamento non solo sugli smartphone. Devi eseguire il test su tablet, dispositivi pieghevoli e altri dispositivi. Scopri di più su come testare diverse dimensioni dello schermo.
Tipi di test UI
Questa sezione illustra due tipi di test dell'interfaccia utente:
I test di comportamento analizzano la gerarchia dell'interfaccia utente per fare affermazioni sulle proprietà degli elementi dell'interfaccia utente.
I test di screenshot acquisiscono screenshot di un'interfaccia utente e li confrontano con immagini approvate in precedenza.
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,["# Automate UI tests\n\nTesting user interactions helps ensure users don't encounter unexpected results\nor have a poor experience when interacting with your app. You should get into\nthe habit of creating user interface (UI) tests if you need to verify that the\nUI of your app is functioning correctly.\n\nOne approach to UI testing is to have a human tester perform a set of user\noperations on the target app and verify that it is behaving correctly. However,\nthis manual approach can be time-consuming and error-prone. A more efficient\napproach is to write your UI tests such that user actions are performed in an\nautomated way. The automated approach lets you run your tests quickly and\nreliably in a repeatable manner.\n\nUI tests launch an app (or part of it), then simulate user interactions, and\nfinally check that the app reacted appropriately. They are integration tests\nthat can range from verifying the behavior of a small component to a large\nnavigation test that traverses a whole user flow. They are useful to check for\nregressions and to verify compatibility with different API levels and physical\ndevices.\n\nRun UI tests\n------------\n\n- To run [instrumented](/training/testing/instrumented-tests) UI tests using Android Studio, you implement your test code in a separate Android test folder - `src/androidTest/java`. The [Android Gradle Plugin](/studio/releases/gradle-plugin) builds a test app based on your test code, then loads the test app on the same device as the target app. In your test code, you can use UI testing frameworks to simulate user interactions on the target app, in order to perform testing tasks that cover specific usage scenarios.\n- You can also use [Robolectric](/training/testing/local-tests/robolectric#ui-testing) to run UI tests on the JVM.\n\nArchitecture and test setup\n---------------------------\n\nThe architecture of your app should let tests replace parts of it for [testing\ndoubles](/training/testing/fundamentals/test-doubles) and you should use libraries that provide utilities to help with\ntesting. For example, you can replace a data repository module with an in-memory\nversion of it that provides fake, deterministic data to the test.\n\n\u003cbr /\u003e\n\n**Figure 3**: Testing a UI by replacing its dependencies with fakes.\n\n\u003cbr /\u003e\n\nThe recommended approach to replace dependencies is dependency injection. You\ncan create your own system [manually](/training/dependency-injection/manual) but we recommend using a DI framework\nlike [Hilt](/training/dependency-injection/hilt-android) for this.\n\nWhy test UIs automatically?\n---------------------------\n\nAn Android app can target thousands of different devices across many API levels\nand form factors, and the high level of customization that the OS brings to the\nuser means your app could be rendered incorrectly or even crash on some devices.\n\nUI testing lets you do *compatibility testing*, verifying the behavior of an app\nin different contexts. You might want to run your UI tests on devices that vary\nin the following ways:\n\n- **API level**: 21, 25, and 30.\n- **Locale**: English, Arabic, and Chinese.\n- **Orientation**: Portrait, landscape.\n\nMoreover, apps should check the behavior beyond phones. You should test on\ntablets, foldables, and other devices. Read more about [testing different screen\nsizes](/training/testing/different-screens).\n\nTypes of UI Tests\n-----------------\n\nThis section covers two types of UI tests:\n\n- [Behavior tests](/training/testing/ui-tests/behavior) analyze the UI hierarchy to make assertions on the properties of the UI elements.\n- [Screenshot tests](/training/testing/ui-tests/screenshot) take screenshots of a UI and compares them with a previously-approved images."]]