AndroidX 테스트에는 AndroidJUnitRunner입니다. JUnit 규칙은 유연성을 높이고 테스트에 필요한 상용구 코드가 있어야 합니다. 예를 들어, 확인할 수 있습니다.
ActivityScenarioRule
이 규칙은 단일 활동의 기능 테스트를 제공합니다. 규칙 실행
@Test
주석이 달린 각 테스트 전뿐 아니라
@Before
주석이 달린 모든 메서드 이 규칙은
테스트가 완료되고 @After
주석이 달린 모든 메서드가 완료됩니다. 주어진
테스트 로직에서 실행 가능한 경우
ActivityScenarioRule.getScenario().onActivity()
다음 코드 스니펫은
다음과 같이 테스트 로직에 ActivityScenarioRule
를 추가합니다.
@RunWith(AndroidJUnit4::class.java)
@LargeTest
class MyClassTest {
@get:Rule
val activityRule = ActivityScenarioRule(MyClass::class.java)
@Test fun myClassMethod_ReturnsTrue() {
activityRule.scenario.onActivity { … } // Optionally, access the activity.
}
}
public class MyClassTest {
@Rule
public ActivityScenarioRule<MyClass> activityRule =
new ActivityScenarioRule(MyClass.class);
@Test
public void myClassMethod_ReturnsTrue() { ... }
}
ServiceTestRule
이 규칙은
종료하는 것입니다 다음을 사용하여 서비스를 시작하거나 바인드할 수 있습니다.
도우미 메서드 중 하나입니다. 테스트 후 자동으로 중지되거나 결합이 해제됩니다.
완료되고 @After
주석이 달린 메서드가 완료된 것입니다.
@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 규칙을 사용하는 방법에 관한 자세한 내용은 확인할 수 있습니다
문서
- 프래그먼트 테스트 가이드를 사용하여 프래그먼트를 개별적으로 테스트합니다.
- Compose 레이아웃 테스트: Compose로 만든 UI를 테스트합니다.
샘플
- BasicSample:
ActivityScenarioRule
의 간단한 사용법입니다.