AndroidX 테스트에는 AndroidJUnitRunner
와 함께 사용되는 JUnit 규칙 세트가 포함되어 있습니다. JUnit 규칙은 유연성을 높이고 테스트에 필요한 상용구 코드를 줄입니다.
ActivityTestRule
이 규칙은 단일 활동의 기능 테스트를 제공합니다. 테스트 중인 활동은 @Test
주석이 달린 각 테스트 및 @Before
주석이 달린 메서드 이전에 시작되며, 테스트가 완료되고 @After
주석이 달린 모든 메서드가 완료된 이후에 종료됩니다. 테스트 로직에서 테스트 중인 활동에 액세스하려면 ActivityTestRule.getActivity()
를 호출합니다.
참고: AndroidX 테스트에는 현재 베타 버전으로 제공되는 ActivityScenario
라는 또 다른 API가 포함되어 있습니다. 이 API는 다양한 테스트 환경에서 작동하며 이 API를 사용하는 테스트 내에서 스레드 안전을 제공합니다.
이 API를 사용해 보고 앱 활동의 수명 주기를 촉진하는 데 도움이 되는 방법을 알아보세요.
다음 코드 스니펫은 ActivityTestRule
을 테스트 로직에 통합하는 방법을 보여줍니다.
Kotlin
@RunWith(AndroidJUnit4::class.java) @LargeTest class MyClassTest { @get:Rule val activityRule = ActivityTestRule(MyClass::class.java) @Test fun myClassMethod_ReturnsTrue() { ... } }
자바
@RunWith(AndroidJUnit4.class) @LargeTest public class MyClassTest { @Rule public ActivityTestRule<MyClass> activityRule = new ActivityTestRule(MyClass.class); @Test public void myClassMethod_ReturnsTrue() { ... } }
ServiceTestRule
이 규칙은 테스트 전후에 서비스를 시작하고 종료하는 간소화된 메커니즘을 제공합니다. 또한 서비스를 시작하거나 서비스와 결합할 때 서비스가 성공적으로 연결되도록 보장합니다. 도우미 메서드 중 하나를 사용하여 서비스를 시작하거나 결합할 수 있습니다. 테스트가 완료되고 @After
주석이 달린 메서드가 완료된 후 서비스가 자동으로 중지되거나 결합 해제됩니다.
Kotlin
@RunWith(AndroidJUnit4::class.java) @MediumTest class MyServiceTest { @get:Rule val serviceRule = ServiceTestRule() @Test fun testWithStartedService() { serviceRule.startService( Intent(ApplicationProvider.getApplicationContext<Context>(), MyService::class.java)) // Add your test code here. } @Test fun testWithBoundService() { val binder = serviceRule.bindService( Intent(ApplicationProvider.getApplicationContext(), MyService::class.java)) val service = (binder as MyService.LocalBinder).service assertThat(service.doSomethingToReturnTrue()).isTrue() } }
자바
@RunWith(AndroidJUnit4.class) @MediumTest public class MyServiceTest { @Rule public final ServiceTestRule serviceRule = new ServiceTestRule(); @Test public void testWithStartedService() { serviceRule.startService( new Intent(ApplicationProvider.getApplicationContext(), MyService.class)); // Add your test code here. } @Test public void testWithBoundService() { IBinder binder = serviceRule.bindService( new Intent(ApplicationProvider.getApplicationContext(), MyService.class)); MyService service = ((MyService.LocalBinder) binder).getService(); assertThat(service.doSomethingToReturnTrue()).isTrue(); } }
참고 자료
Android 테스트에서 JUnit 규칙을 사용하는 방법에 관한 자세한 내용은 다음 자료를 참조하세요.
샘플
- BasicSample:
ActivityTestRule
의 간단한 사용법입니다.