AndroidJUnitRunner

AndroidJUnitRunner 클래스는 EspressoUI Automator 테스트 프레임워크를 사용하는 것을 비롯하여 Android 기기에서 JUnit 3 또는 JUnit 4 스타일 테스트 클래스를 실행할 수 있는 JUnit 테스트 실행기입니다.

이 테스트 실행기는 테스트 패키지와 테스트 대상 앱을 기기에 로드하여 테스트를 실행하고 테스트 결과를 보고하는 역할을 합니다. 이 클래스는 JUnit 3 테스트만 지원하는 InstrumentationTestRunner 클래스를 대체합니다.

이 테스트 실행기는 다음을 포함하여 몇 가지 일반적인 테스트 작업을 지원합니다.

JUnit 테스트 작성

이 테스트 실행기는 JUnit 3 및 JUnit 4(JUnit 4.10까지) 테스트와 호환됩니다. 하지만 예기치 않은 결과가 발생할 수 있으므로 같은 패키지에서 JUnit 3 테스트 코드와 JUnit 4 테스트 코드를 함께 사용하지 않아야 합니다. 기기나 에뮬레이터에서 실행할 계측 JUnit 4 테스트 클래스를 만든다면 테스트 클래스 앞에 @RunWith(AndroidJUnit4.class) 주석을 붙여야 합니다.

다음 코드 스니펫은 ChangeTextBehavior 클래스의 changeText 작업이 올바르게 작동하는지 검증하기 위해 계측 JUnit 4 테스트를 작성하는 방법을 보여줍니다.

Kotlin

    @RunWith(AndroidJUnit4::class)
    @LargeTest
    class ChangeTextBehaviorTest {
        val stringToBeTyped = "Espresso"
        @get:Rule
        val activityRule = ActivityTestRule(MainActivity::class.java)

        @Test fun changeText_sameActivity() {
            // Type text and then press the button.
            onView(withId(R.id.editTextUserInput))
                .perform(typeText(stringToBeTyped), closeSoftKeyboard())
            onView(withId(R.id.changeTextBt)).perform(click())

            // Check that the text was changed.
            onView(withId(R.id.textToBeChanged))
                .check(matches(withText(stringToBeTyped)))
        }
    }
    

자바

    @RunWith(AndroidJUnit4.class)
    @LargeTest
    public class ChangeTextBehaviorTest {

        private static final String stringToBeTyped = "Espresso";

        @Rule
        public ActivityTestRule<MainActivity> activityRule =
                new ActivityTestRule<>(MainActivity.class);

        @Test
        public void changeText_sameActivity() {
            // Type text and then press the button.
            onView(withId(R.id.editTextUserInput))
                    .perform(typeText(stringToBeTyped), closeSoftKeyboard());
            onView(withId(R.id.changeTextBt)).perform(click());

            // Check that the text was changed.
            onView(withId(R.id.textToBeChanged))
                    .check(matches(withText(stringToBeTyped)));
        }
    }
    

Android Test Orchestrator 사용

AndroidJUnitRunner 버전 1.0 이상을 사용하는 경우 앱의 자체 Instrumentation 호출 내에서 각 앱의 테스트를 실행할 수 있는 Android Test Orchestrator 도구에 액세스할 수 있습니다.

Android Test Orchestrator는 테스트 환경에 다음과 같은 이점을 제공합니다.

  • 최소 공유 상태. 각 테스트는 자체 Instrumentation 인스턴스에서 실행됩니다. 따라서 테스트가 앱 상태를 공유하는 경우 각 테스트 후 이러한 공유 상태 대부분이 기기의 CPU 또는 메모리에서 삭제됩니다.

    각 테스트 후 모든 공유 상태를 기기의 CPU와 메모리에서 삭제하려면 clearPackageData 플래그를 사용하세요.

  • 비정상 종료가 격리됩니다. 테스트 하나가 비정상 종료되더라도 자체 Instrumentation 인스턴스만 삭제하므로 모음에 있는 나머지 테스트는 계속 실행됩니다.

Android 스튜디오와 Firebase Test Lab 모두에는 Android Test Orchestrator가 사전 설치되어 있지만 Android 스튜디오에서는 이 기능을 사용 설정해야 합니다.

그러나 다른 도구 모음을 사용하여 앱을 테스트하는 경우 다음 단계를 완료하여 Android Test Orchestrator를 계속 사용할 수 있습니다.

  1. 필요한 패키지를 앱의 빌드 파일에 포함합니다.
  2. 명령줄에서 Android Test Orchestrator를 사용 설정합니다.

Gradle에서 사용 설정

Gradle 명령줄 도구를 사용하여 Android Test Orchestrator를 사용 설정하려면 다음 단계를 완료하세요.

  1. 프로젝트의 build.gradle 파일에 다음 구문을 추가합니다.

        android {
          defaultConfig {
           ...
           testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    
           // The following argument makes the Android Test Orchestrator run its
           // "pm clear" command after each test invocation. This command ensures
           // that the app's state is completely cleared between tests.
           testInstrumentationRunnerArguments clearPackageData: 'true'
         }
    
          testOptions {
            execution 'ANDROIDX_TEST_ORCHESTRATOR'
          }
        }
    
        dependencies {
          androidTestImplementation 'androidx.test:runner:1.1.0'
          androidTestUtil 'androidx.test:orchestrator:1.1.0'
        }
  2. 다음 명령어를 실행하여 Android Test Orchestrator를 실행합니다.

        ./gradlew connectedCheck

Android 스튜디오에서 사용 설정

Android Test Orchestrator는 Android 스튜디오 3.0 이상에서 지원됩니다. Android 스튜디오에서 Android Test Orchestrator를 사용 설정하려면 Gradle에서 사용 설정에 나온 구문을 앱의 build.gradle 파일에 추가합니다.

명령줄에서 사용 설정

명령줄에서 Android Test Orchestrator를 사용하려면 터미널 창에서 다음 명령어를 실행하세요.

    # Install the test orchestrator.
    adb install -r path/to/m2repository/androidx/test/orchestrator/1.1.0/orchestrator-1.1.0.apk

    # Install test services.
    adb install -r path/to/m2repository/androidx/test/services/test-services/1.1.0/test-services-1.1.0.apk

    # Replace "com.example.test" with the name of the package containing your tests.
    # Add "-e clearPackageData true" to clear your app's data in between runs.
    adb shell 'CLASSPATH=$(pm path androidx.test.services) app_process / \
      androidx.test.services.shellexecutor.ShellMain am instrument -w -e \
      targetInstrumentation com.example.test/androidx.test.runner.AndroidJUnitRunner \
      androidx.test.orchestrator/.AndroidTestOrchestrator'
    

명령어 구문에 표시된 대로 Android Test Orchestrator를 설치한 다음 바로 사용합니다.

참고: 타겟 계측을 모르는 경우 다음 명령어를 실행하여 찾을 수 있습니다.

    adb shell pm list instrumentation

아키텍처

그림 1에서와 같이 Orchestrator 서비스 APK는 테스트 APK 및 테스트 중인 앱의 APK와 별도의 프로세스에 저장됩니다.

그림 1. Android Test Orchestrator APK 구조

Android Test Orchestrator는 테스트 모음 실행을 시작할 때 JUnit 테스트를 수집한 다음 자체 Instrumentation 인스턴스에서 개별적으로 각 테스트를 실행합니다.

앱 환경설정에 액세스

테스트 중인 앱의 컨텍스트를 가져오려면 정적 ApplicationProvider.getApplicationContext() 메서드를 호출하세요. 앱에서 Application의 맞춤 서브클래스를 만든 경우 이 메서드는 맞춤 서브클래스의 컨텍스트를 반환합니다.

개발자가 도구 구현자라면 InstrumentationRegistry 클래스를 사용하여 하위 수준 테스트 API에 액세스할 수 있습니다. 이 클래스에는 Instrumentation 객체, 타겟 앱 Context 객체, 테스트 앱 Context 객체 및 테스트에 전달되는 명령줄 인수가 포함되어 있습니다. 이 데이터는 UI Automator 프레임워크를 사용하여 테스트를 작성하거나 테스트가 앱의 컨텍스트에 종속된 경우에 유용합니다.

테스트 필터링

JUnit 4.x 테스트에서는 주석을 사용하여 테스트 실행을 구성할 수 있습니다. 이 기능 덕분에 테스트에서 상용구 코드와 조건 코드를 추가할 필요성이 최소화됩니다. JUnit 4에서 지원되는 표준 주석 외에도, 이 테스트 실행기는 다음을 포함한 Android 고유의 주석도 지원합니다.

  • @RequiresDevice: 에뮬레이터가 아니라 실제 기기에서만 테스트를 실행해야 한다고 지정합니다.
  • @SdkSuppress: 지정된 수준보다 낮은 Android API 수준에서는 테스트가 실행되지 않도록 억제합니다. 예를 들어 23보다 낮은 모든 API 수준에서 테스트 실행을 억제하려면 주석 @SDKSuppress(minSdkVersion=23)을 사용하세요.
  • @SmallTest, @MediumTest, @LargeTest: 테스트를 실행하는 데 걸리는 시간과 테스트를 실행할 수 있는 빈도를 분류합니다.

테스트 샤딩

테스트 실행기는 단일 테스트 모음을 여러 샤드로 분할하는 기능을 지원하므로 같은 Instrumentation 인스턴스에서 같은 샤드에 속하는 테스트를 그룹으로 묶어 손쉽게 실행할 수 있습니다. 각각의 샤드는 색인 번호로 식별됩니다. 테스트를 실행할 때 만들 개별 샤드 수를 지정하려면 -e numShards 옵션을 사용하고 실행할 샤드를 지정하려면 -e shardIndex 옵션을 사용하세요.

예를 들어, 테스트 모음을 10개의 샤드로 분할하고 두 번째 샤드에 그룹화된 테스트만 실행하려면 다음 명령어를 사용하세요.

    adb shell am instrument -w -e numShards 10 -e shardIndex 2
    

추가 정보

이 테스트 실행기의 사용 방법을 자세히 알아보려면 API 참조를 확인해 보세요.

AndroidJUnitRunner 클래스를 사용하려면 AndroidX 테스트용 프로젝트 설정에 설명된 대로 이 클래스를 프로젝트 패키지 중 하나로 포함하세요.

추가 리소스

AndroidJUnitRunner 사용에 관한 자세한 내용은 다음 리소스를 참조하세요.

샘플

  • AndroidJunitRunnerSample: 테스트 주석, 매개변수화된 테스트 및 테스트 모음 생성을 보여줍니다.