Koleksiyonlar ile düzeninizi koruyun
İçeriği tercihlerinize göre kaydedin ve kategorilere ayırın.
AndroidX Testi,AndroidJUnitRunner'ı açın. JUnit kuralları daha fazla esneklik sağlar ve
testlerde gereken ortak metin kodu. Örneğin, bir ekip üyesiyle aynı anda bir
belirli bir aktiviteye dokunun.
EtkinlikSenaryosuKural
Bu kural, tek bir etkinliğin işlevsel testini sağlar. Kural başlatılır
seçilen etkinlik her testten önce ve @Test ile ek açıklama olarak verilir.
@Before ile başlayan herhangi bir yöntem. Kural, şu tarihten sonra etkinliği sonlandırır:
test tamamlandı ve @After ile açıklama eklenen tüm yöntemler tamamlanır. Verilen
etkinliği olması için, Search Console'da çalıştırılabilir bir
ActivityScenarioRule.getScenario().onActivity()
Aşağıdaki kod snippet'i
Test mantığınıza ActivityScenarioRule ekleyin:
Kotlin
@RunWith(AndroidJUnit4::class.java)@LargeTestclassMyClassTest{@get:RulevalactivityRule=ActivityScenarioRule(MyClass::class.java)@TestfunmyClassMethod_ReturnsTrue(){activityRule.scenario.onActivity{…}// Optionally, access the activity.}}
Bu kural,
ve öncesinde ya da sonrasında kapatmaktır. Hizmeti şununla başlatabilir veya bağlayabilirsiniz:
diğer yöntemlerden biridir. Testten sonra otomatik olarak durur veya bağlantısı kesilir
tamamlandı. @After ile ek açıklama eklenen tüm yöntemler tamamlandı.
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();}}
Ek kaynaklar
Android testlerinde JUnit kurallarını kullanma hakkında daha fazla bilgi için şu sayfaya bakın:
inceleyebilirsiniz.
BasicSample: ActivityScenarioRule basit kullanımı.
Bu sayfadaki içerik ve kod örnekleri, İçerik Lisansı sayfasında açıklanan lisanslara tabidir. Java ve OpenJDK, Oracle ve/veya satış ortaklarının tescilli ticari markasıdır.
Son güncelleme tarihi: 2025-07-27 UTC.
[[["Anlaması kolay","easyToUnderstand","thumb-up"],["Sorunumu çözdü","solvedMyProblem","thumb-up"],["Diğer","otherUp","thumb-up"]],[["İhtiyacım olan bilgiler yok","missingTheInformationINeed","thumb-down"],["Çok karmaşık / çok fazla adım var","tooComplicatedTooManySteps","thumb-down"],["Güncel değil","outOfDate","thumb-down"],["Çeviri sorunu","translationIssue","thumb-down"],["Örnek veya kod sorunu","samplesCodeIssue","thumb-down"],["Diğer","otherDown","thumb-down"]],["Son güncelleme tarihi: 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`."]]