Mantieni tutto organizzato con le raccolte
Salva e classifica i contenuti in base alle tue preferenze.
Il test AndroidX include un insieme di regole JUnit da utilizzare con
AndroidJUnitRunner Le regole JUnit offrono maggiore flessibilità e riducono
il codice boilerplate richiesto nei test. Ad esempio, possono essere usate per avviare
per un'attività specifica.
Regola dello scenario di attività
Questa regola fornisce i test funzionali di una singola attività. La regola viene avviata
l'attività scelta prima di ogni test annotata con @Test, nonché prima
qualsiasi metodo annotato con @Before. La regola termina l'attività dopo
test completati e tutti i metodi annotati con @After di completamento. Per accedere ai dati forniti
attività nella logica di test, fornisci un callback eseguibile
ActivityScenarioRule.getScenario().onActivity().
Il seguente snippet di codice mostra come incorporare
ActivityScenarioRule nella logica di test:
Kotlin
@RunWith(AndroidJUnit4::class.java)@LargeTestclassMyClassTest{@get:RulevalactivityRule=ActivityScenarioRule(MyClass::class.java)@TestfunmyClassMethod_ReturnsTrue(){activityRule.scenario.onActivity{…}// Optionally, access the activity.}}
Questa regola fornisce un meccanismo semplificato per avviare il servizio prima che
i test e arrestarlo prima e dopo. Puoi avviare o associare il servizio con
uno dei metodi helper. Si interrompe o si slega automaticamente dopo il test
vengono completati e tutti i metodi annotati con @After sono terminati.
Kotlin
@RunWith(AndroidJUnit4::class.java)@MediumTestclassMyServiceTest{@get:RulevalserviceRule=ServiceTestRule()@TestfuntestWithStartedService(){serviceRule.startService(Intent(ApplicationProvider.getApplicationContext<Context>(),MyService::class.java))// Add your test code here.}@TestfuntestWithBoundService(){valbinder=serviceRule.bindService(Intent(ApplicationProvider.getApplicationContext(),MyService::class.java))valservice=(binderasMyService.LocalBinder).serviceassertThat(service.doSomethingToReturnTrue()).isTrue()}}
Java
@RunWith(AndroidJUnit4.class)@MediumTestpublicclassMyServiceTest{@RulepublicfinalServiceTestRuleserviceRule=newServiceTestRule();@TestpublicvoidtestWithStartedService(){serviceRule.startService(newIntent(ApplicationProvider.getApplicationContext(),MyService.class));// Add your test code here.}@TestpublicvoidtestWithBoundService(){IBinderbinder=serviceRule.bindService(newIntent(ApplicationProvider.getApplicationContext(),MyService.class));MyServiceservice=((MyService.LocalBinder)binder).getService();assertThat(service.doSomethingToReturnTrue()).isTrue();}}
Risorse aggiuntive
Per ulteriori informazioni sull'utilizzo delle regole JUnit nei test Android, consulta
le seguenti risorse.
BasicSample: utilizzo semplice di ActivityScenarioRule.
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,["# JUnit4 rules with AndroidX Test\n\nAndroidX Test includes a set of [JUnit rules](https://github.com/junit-team/junit4/wiki/Rules) to be used with the\n[AndroidJUnitRunner](/training/testing/junit-runner). JUnit rules provide more flexibility and reduce the\nboilerplate code required in tests. For example, they can be used to start a\nspecific activity.\n\nActivityScenarioRule\n--------------------\n\nThis rule provides functional testing of a single activity. The rule launches\nthe chosen activity before each test annotated with `@Test`, as well as before\nany method annotated with `@Before`. The rule terminates the activity after the\ntest completes and all methods annotated with `@After` finish. To access the given\nactivity in your test logic, provide a callback runnable to\n`ActivityScenarioRule.getScenario().onActivity()`.\n\nThe following code snippet demonstrates how to incorporate\n`ActivityScenarioRule` into your testing logic: \n\n### Kotlin\n\n```kotlin\n@RunWith(AndroidJUnit4::class.java)\n@LargeTest\nclass MyClassTest {\n @get:Rule\n val activityRule = ActivityScenarioRule(MyClass::class.java)\n\n @Test fun myClassMethod_ReturnsTrue() {\n activityRule.scenario.onActivity { ... } // Optionally, access the activity.\n }\n}\n```\n\n### Java\n\n```java\npublic class MyClassTest {\n @Rule\n public ActivityScenarioRule<MyClass> activityRule =\n new ActivityScenarioRule(MyClass.class);\n\n @Test\n public void myClassMethod_ReturnsTrue() { ... }\n}\n```\n| **Note:** in order to test fragments in isolation, you can use the `FragmentScenario` class from the [AndroidX fragment-testing library](/guide/fragments/test).\n\nServiceTestRule\n---------------\n\nThis rule provides a simplified mechanism to launch your service before the\ntests and shut it down before and after. You can start or bind the service with\none of the helper methods. It automatically stops or unbinds after the test\ncompletes and any methods annotated with `@After` have finished.\n**Note:** This rule doesn't support `IntentService`. This is because the service is destroyed when `IntentService.onHandleIntent(Intent)` finishes all outstanding commands, so there is no guarantee to establish a successful connection in a timely manner. \n\n### Kotlin\n\n```kotlin\n@RunWith(AndroidJUnit4::class.java)\n@MediumTest\nclass MyServiceTest {\n @get:Rule\n val serviceRule = ServiceTestRule()\n\n @Test fun testWithStartedService() {\n serviceRule.startService(\n Intent(ApplicationProvider.getApplicationContext\u003cContext\u003e(),\n MyService::class.java))\n // Add your test code here.\n }\n\n @Test fun testWithBoundService() {\n val binder = serviceRule.bindService(\n Intent(ApplicationProvider.getApplicationContext(),\n MyService::class.java))\n val service = (binder as MyService.LocalBinder).service\n assertThat(service.doSomethingToReturnTrue()).isTrue()\n }\n}\n```\n\n### Java\n\n```java\n@RunWith(AndroidJUnit4.class)\n@MediumTest\npublic class MyServiceTest {\n @Rule\n public final ServiceTestRule serviceRule = new ServiceTestRule();\n\n @Test\n public void testWithStartedService() {\n serviceRule.startService(\n new Intent(ApplicationProvider.getApplicationContext(),\n MyService.class));\n // Add your test code here.\n }\n\n @Test\n public void testWithBoundService() {\n IBinder binder = serviceRule.bindService(\n new Intent(ApplicationProvider.getApplicationContext(),\n MyService.class));\n MyService service = ((MyService.LocalBinder) binder).getService();\n assertThat(service.doSomethingToReturnTrue()).isTrue();\n }\n}\n```\n\nAdditional resources\n--------------------\n\nFor more information about using JUnit rules in Android tests, consult the\nfollowing resources.\n\n### Documentation\n\n- [Test your fragments](/guide/fragments/test) guide, to test fragments in isolation.\n- [Testing your Compose layout](/jetpack/compose/testing), to test UIs made with Compose.\n\n### Samples\n\n- [BasicSample](https://github.com/android/testing-samples/tree/main/ui/espresso/BasicSample): Simple usage of `ActivityScenarioRule`."]]