콘텐츠로 건너뛰기

자주 방문한 페이지

최근 방문한 페이지

navigation

AndroidJUnitRunner

The AndroidJUnitRunner class is a JUnit test runner that lets you run JUnit 3- or JUnit 4-style test classes on Android devices, including those using the Espresso and UI Automator testing frameworks.

The test runner handles loading your test package and the app under test to a device, running your tests, and reporting test results. This class replaces the InstrumentationTestRunner class, which only supports JUnit 3 tests.

This test runner supports several common testing tasks, including the following:

Writing JUnit tests

The test runner is compatible with your JUnit 3 and JUnit 4 (up to JUnit 4.10) tests. However, you should avoid mixing JUnit 3 and JUnit 4 test code in the same package, as this might cause unexpected results. If you are creating an instrumented JUnit 4 test class to run on a device or emulator, your test class must be prefixed with the @RunWith(AndroidJUnit4.class) annotation.

The following code snippet shows how you might write an instrumented JUnit 4 test to validate that the add operation in the CalculatorActivity class works correctly:

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

    private static final String mStringToBeTyped = "Espresso";

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

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

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

Using Android Test Orchestrator

When using AndroidJUnitRunner version 1.0 or higher, you have access to a tool called Android Test Orchestrator, which allows you to run each of your app's tests within its own invocation of Instrumentation.

Android Test Orchestrator offers the following benefits for your testing environment:

To use Android Test Orchestrator, complete the following steps:

  1. Download the necessary packages.
  2. Enable Android Test Orchestrator, either in Android Studio or from the command-line.

Enable from Gradle

To enable Android Test Orchestrator using the Gradle command-line tool, complete these steps:

  1. Add the following statements to your project's build.gradle file:

    android {
      defaultConfig {
       ...
       testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
     }
    
      testOptions {
        execution 'ANDROID_TEST_ORCHESTRATOR'
      }
    }
    
    dependencies {
      androidTestImplementation 'com.android.support.test:runner:1.0.1'
      androidTestUtil 'com.android.support.test:orchestrator:1.0.1'
    }
  2. Run Android Test Orchestrator by executing the following command:

    ./gradlew connectedCheck

Enable from Android Studio

Support for Android Test Orchestrator is available with Android Studio 3.0 and higher. To enable Android Test Orchestrator in Android Studio, add the statements shown in Enable from Gradle to your app's build.gradle file.

Enable from command line

To use Android Test Orchestrator on the command line, run the following commands in a terminal window:

# Install the test orchestrator.
adb install -r path/to/m2repository/com/android/support/test/orchestrator/1.0.1/orchestrator-1.0.1.apk

# Install test services.
adb install -r path/to/m2repository/com/android/support/test/services/test-services/1.0.1/test-services-1.0.1.apk

# Replace "com.example.test" with the name of the package containing your tests.
adb shell 'CLASSPATH=$(pm path android.support.test.services) app_process / \
  android.support.test.services.shellexecutor.ShellMain am instrument -w -e \
  targetInstrumentation com.example.test/android.support.test.runner.AndroidJUnitRunner \
  android.support.test.orchestrator/.AndroidTestOrchestrator'

As the command syntax shows, you install Android Test Orchestrator, then use it directly.

Note: If you don't know your target instrumentation, you can look it up by running the following command:

adb shell pm list instrumentation

Architecture

The Orchestrator service APK is stored in a process that's separate from the test APK and the APK of the app under test, as shown in Figure 1:

Figure 1. Android Test Orchestrator APK structure

Android Test Orchestrator collects JUnit tests at the beginning of your test suite run, but it then executes each test separately, in its own instance of Instrumentation.

Accessing instrumentation information

You can use the InstrumentationRegistry class to access information related to your test run. This class includes the Instrumentation object, the target app Context object, the test app Context object, and the command line arguments passed into your test. This data is useful when you are writing tests using the UI Automator framework or when writing tests that have dependencies on the Instrumentation or Context objects.

Filtering tests

In your JUnit 4.x tests, you can use annotations to configure the test run. This feature minimizes the need to add boilerplate and conditional code in your tests. In addition to the standard annotations supported by JUnit 4, the test runner also supports Android-specific annotations, including the following:

Sharding tests

The test runner supports splitting a single test suite into multiple shards, so you can easily run tests belonging to the same shard together as a group, under the same Instrumentation instance. Each shard is identified by an index number. When running tests, use the -e numShards option to specify the number of separate shards to create and the -e shardIndex option to specify which shard to run.

For example, to split the test suite into 10 shards and run only the tests grouped in the second shard, use the following command:

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

Resources

To learn more about using this test runner, see the API reference.

To use the AndroidJUnitRunner class, include it as one of your project's packages.

이 사이트는 쿠키를 사용하여 사이트별 언어 및 표시 옵션에 대한 환경설정을 저장합니다.

Google Play에서 성공을 거두는 데 도움이 되는 최신 Android 개발자 뉴스 및 도움말을 받아 보세요.

* 필수 입력란

완료되었습니다.

WeChat에서 Google Developers 팔로우하기

이 사이트를 (으)로 탐색할까요?

페이지를 요청했지만 이 사이트의 언어 환경설정은 입니다.

언어 환경설정을 변경하고 이 사이트를 (으)로 탐색할까요? 언어 환경설정을 나중에 변경하려면 각 페이지 하단의 언어 메뉴를 사용하세요.

이 클래스를 사용하려면 API 수준 이상이 필요합니다.

문서에 대해 선택한 API 수준이 이므로 이 문서가 표시되지 않습니다. 왼쪽 탐색 메뉴의 선택기로 문서 API 수준을 변경할 수 있습니다.

앱에 필요한 API 수준 지정에 관한 자세한 내용은 다양한 플랫폼 버전 지원을 참조하세요.

Take a short survey?
Help us improve the Android developer experience. (April 2018 — Developer Survey)