@RunWith(AndroidJUnit4::class.java)@LargeTestclassMyClassTest{@get:RulevalactivityRule=ActivityScenarioRule(MyClass::class.java)@TestfunmyClassMethod_ReturnsTrue(){activityRule.scenario.onActivity{…}// Optionally, access the activity.}}
@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();}}
[null,null,["最后更新时间 (UTC):2025-07-27。"],[],[],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`."]]