Tetap teratur dengan koleksi
Simpan dan kategorikan konten berdasarkan preferensi Anda.
AndroidX Test mencakup serangkaian aturan JUnit untuk digunakan dengan
AndroidJUnitRunner. Aturan JUnit memberikan lebih banyak fleksibilitas dan mengurangi
kode boilerplate yang diperlukan dalam pengujian. Misalnya, mereka dapat digunakan untuk memulai
aktivitas tertentu.
ActivityScenarioRule
Aturan ini menyediakan pengujian fungsional satu aktivitas. Aturan diluncurkan
aktivitas yang dipilih sebelum setiap pengujian dianotasi dengan @Test, serta sebelumnya
metode apa pun yang dianotasi dengan @Before. Aturan ini menghentikan aktivitas setelah
pengujian selesai dan semua metode yang dianotasi dengan selesai @After. Untuk mengakses
aktivitas dalam logika pengujian Anda, sediakan callback yang dapat dijalankan ke
ActivityScenarioRule.getScenario().onActivity().
Cuplikan kode berikut menunjukkan cara menerapkan
ActivityScenarioRule ke logika pengujian Anda:
Kotlin
@RunWith(AndroidJUnit4::class.java)@LargeTestclassMyClassTest{@get:RulevalactivityRule=ActivityScenarioRule(MyClass::class.java)@TestfunmyClassMethod_ReturnsTrue(){activityRule.scenario.onActivity{…}// Optionally, access the activity.}}
Aturan ini menyediakan mekanisme yang disederhanakan untuk meluncurkan layanan Anda sebelum
tes dan mematikannya sebelum dan sesudahnya. Anda dapat memulai atau mengikat
layanan dengan
salah satu metode bantuan. Otomatis berhenti atau melepas ikatan setelah pengujian
selesai dan semua metode yang dianotasi dengan @After telah selesai.
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();}}
Referensi lainnya
Untuk informasi selengkapnya tentang menggunakan aturan JUnit dalam pengujian Android, lihat
referensi berikut.
BasicSample: Penggunaan sederhana ActivityScenarioRule.
Konten dan contoh kode di halaman ini tunduk kepada lisensi yang dijelaskan dalam Lisensi Konten. Java dan OpenJDK adalah merek dagang atau merek dagang terdaftar dari Oracle dan/atau afiliasinya.
Terakhir diperbarui pada 2025-07-27 UTC.
[null,null,["Terakhir diperbarui pada 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`."]]