Testare il layout di Compose
Mantieni tutto organizzato con le raccolte
Salva e classifica i contenuti in base alle tue preferenze.
Testa la UI della tua app per verificare che il comportamento del codice Compose sia corretto. In questo modo, puoi rilevare gli errori in anticipo e migliorare la qualità della tua app.
Compose fornisce un insieme di API di test per trovare elementi, verificarne gli
attributi ed eseguire azioni utente. Le API includono anche funzionalità avanzate
come la manipolazione del tempo. Utilizza queste API per creare test solidi che verifichino
il comportamento della tua app.
Visualizzazioni
Se utilizzi le visualizzazioni anziché Compose, consulta la sezione generale Testare le app su
Android.
In particolare, un buon punto di partenza è la guida Automatizzare i test dell'interfaccia utente. Spiega come automatizzare i test eseguiti sul dispositivo, anche quando utilizzi le visualizzazioni.
Concetti principali
Di seguito sono riportati alcuni concetti chiave per testare il codice Compose:
- Semantica: la semantica dà significato alla tua UI, consentendo ai test di
interagire con elementi specifici.
- API di test: le API di test ti consentono di trovare elementi, verificarne gli
attributi ed eseguire azioni utente.
- Sincronizzazione: la sincronizzazione verifica che i test attendano che l'interfaccia utente sia inattiva prima di eseguire azioni o fare asserzioni.
- Interoperabilità: l'interoperabilità consente ai test di funzionare con elementi basati su Compose e View nella stessa app.
Foglio informativo sui test
Consulta il cheat sheet per i test per una panoramica di tutti gli argomenti chiave che devi
imparare sui test in Compose.
Configura
Configura l'app per testare il codice Compose.
Innanzitutto, aggiungi le seguenti dipendenze al file build.gradle
del modulo
contenente i test dell'interfaccia utente:
// Test rules and transitive dependencies:
androidTestImplementation("androidx.compose.ui:ui-test-junit4:$compose_version")
// Needed for createComposeRule(), but not for createAndroidComposeRule<YourActivity>():
debugImplementation("androidx.compose.ui:ui-test-manifest:$compose_version")
Questo modulo include un ComposeTestRule
e un'implementazione per Android
chiamata AndroidComposeTestRule
. Tramite questa regola puoi impostare la composizione
dei contenuti o accedere all'attività. Le regole vengono create utilizzando le funzioni di fabbrica,
createComposeRule
o, se devi accedere a un'attività,
createAndroidComposeRule
. Un test UI tipico per Compose ha questo aspetto:
// file: app/src/androidTest/java/com/package/MyComposeTest.kt
class MyComposeTest {
@get:Rule val composeTestRule = createComposeRule()
// use createAndroidComposeRule<YourActivity>() if you need access to
// an activity
@Test
fun myTest() {
// Start the app
composeTestRule.setContent {
MyAppTheme {
MainScreen(uiState = fakeUiState, /*...*/)
}
}
composeTestRule.onNodeWithText("Continue").performClick()
composeTestRule.onNodeWithText("Welcome").assertIsDisplayed()
}
}
Risorse aggiuntive
- Testare le app su Android: la pagina di destinazione principale dei test Android offre una visione più ampia delle tecniche e delle nozioni di base dei test.
- Nozioni di base sui test: scopri di più
sui concetti fondamentali alla base del test di un'app per Android.
- Test locali: puoi eseguire alcuni test
localmente, sulla tua workstation.
- Test strumentati: è buona
norma eseguire anche test strumentati. ovvero test eseguiti direttamente
sul dispositivo.
- Integrazione continua:
l'integrazione continua consente di integrare i test nella pipeline di deployment.
- Testa diverse dimensioni dello schermo: con
molti dispositivi a disposizione degli utenti, devi eseguire test per diverse dimensioni
dello schermo.
- Espresso: sebbene sia destinato alle UI basate sulla visualizzazione, la conoscenza di Espresso può comunque essere utile per alcuni aspetti dei test di Compose.
Codelab
Per saperne di più, prova il codelab Jetpack Compose Testing.
Campioni
Consigliati per te
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-08-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-08-27 UTC."],[],[],null,["Test your app's UI to verify that behavior of your Compose code is\ncorrect. This lets you catch errors early and improve the quality of your app.\n\nCompose provides a set of testing APIs to find elements, verify their\nattributes, and perform user actions. The APIs also include advanced features\nsuch as time manipulation. Use these APIs to create robust tests that verify\nyour app's behavior.\n| **Important:** For more on testing Android apps in general, including testing `View` elements, see the [general testing section](/training/testing). A good place to start is the [Fundamentals of testing Android apps](/training/testing/fundamentals) guide.\n\nViews\n\nIf you are working with views instead of Compose, see the general [Test apps on\nAndroid](/training/testing) section.\n\nIn particular, a good place to start is the [Automate UI tests](/training/testing/ui-tests) guide. It\nlays out how you can automate tests that run on-device, including when using\nviews.\n\nKey Concepts\n\nThe following are some key concepts for testing your Compose code:\n\n- **[Semantics](/develop/ui/compose/testing/semantics)**: Semantics give meaning to your UI, allowing tests to interact with specific elements.\n- **[Testing APIs](/develop/ui/compose/testing/apis)**: Testing APIs let you find elements, verify their attributes, and perform user actions.\n- **[Synchronization](/develop/ui/compose/testing/synchronization)**: Synchronization verifies that tests wait for the UI to be idle before performing actions or making assertions.\n- **[Interoperability](/develop/ui/compose/testing/interoperability)**: Interoperability enables tests to work with both Compose and View-based elements in the same app.\n\nTesting cheatsheet\n\nSee the [testing cheatsheet](/develop/ui/compose/testing/testing-cheatsheet) for an overview of all the key topics you should\nlearn about testing in Compose.\n\nSetup\n\nSet up your app to let you test compose code.\n\nFirst, add the following dependencies to the `build.gradle` file of the module\ncontaining your UI tests: \n\n // Test rules and transitive dependencies:\n androidTestImplementation(\"androidx.compose.ui:ui-test-junit4:$compose_version\")\n // Needed for createComposeRule(), but not for createAndroidComposeRule\u003cYourActivity\u003e():\n debugImplementation(\"androidx.compose.ui:ui-test-manifest:$compose_version\")\n\nThis module includes a [`ComposeTestRule`](/reference/kotlin/androidx/compose/ui/test/junit4/ComposeTestRule) and an implementation for Android\ncalled [`AndroidComposeTestRule`](/reference/kotlin/androidx/compose/ui/test/junit4/AndroidComposeTestRule). Through this rule you can set Compose\ncontent or access the activity. You construct the rules using factory functions,\neither [`createComposeRule`](/reference/kotlin/androidx/compose/ui/test/junit4/package-summary#createComposeRule()) or, if you need access to an activity,\n[`createAndroidComposeRule`](/reference/kotlin/androidx/compose/ui/test/junit4/package-summary#createAndroidComposeRule()). A typical UI test for Compose looks like this: \n\n // file: app/src/androidTest/java/com/package/MyComposeTest.kt\n\n class MyComposeTest {\n\n @get:Rule val composeTestRule = createComposeRule()\n // use createAndroidComposeRule\u003cYourActivity\u003e() if you need access to\n // an activity\n\n @Test\n fun myTest() {\n // Start the app\n composeTestRule.setContent {\n MyAppTheme {\n MainScreen(uiState = fakeUiState, /*...*/)\n }\n }\n\n composeTestRule.onNodeWithText(\"Continue\").performClick()\n\n composeTestRule.onNodeWithText(\"Welcome\").assertIsDisplayed()\n }\n }\n\nAdditional Resources\n\n- **[Test apps on Android](/training/testing)**: The main Android testing landing page provides a broader view of testing fundamentals and techniques.\n- **[Fundamentals of testing](/training/testing/fundamentals):** Learn more about the core concepts behind testing an Android app.\n- **[Local tests](/training/testing/local-tests):** You can run some tests locally, on your own workstation.\n- **[Instrumented tests](/training/testing/instrumented-tests):** It is good practice to also run instrumented tests. That is, tests that run directly on-device.\n- **[Continuous integration](/training/testing/continuous-integration):** Continuous integration lets you integrate your tests into your deployment pipeline.\n- **[Test different screen sizes](/training/testing/different-screens):** With some many devices available to users, you should test for different screen sizes.\n- **[Espresso](/training/testing/espresso)**: While intended for View-based UIs, Espresso knowledge can still be helpful for some aspects of Compose testing.\n\nCodelab\n\nTo learn more, try the [Jetpack Compose Testing codelab](/codelabs/jetpack-compose-testing).\n\nSamples\n\nRecommended for you\n\n- Note: link text is displayed when JavaScript is off\n- [Semantics in Compose](/develop/ui/compose/semantics)\n- [Window insets in Compose](/develop/ui/compose/layouts/insets)\n- [Other considerations](/develop/ui/compose/migrate/other-considerations)"]]