1

打开应用的

  • build.gradle 文件。这通常不是顶级 build.gradle ,而是 app/build.gradle
  • 在 dependencies 节点下添加以下行:
androidTestCompile 'com.android.support.test.espresso:espresso-core:3.0.1'
androidTestCompile 'com.android.support.test:runner:1.0.1'

或者来个大合集

dependencies {
  // AndroidJUnitRunner and JUnit Rules
  androidTestCompile 'com.android.support.test:runner:1.0.1'
  androidTestCompile 'com.android.support.test:rules:1.0.1'

  // Espresso dependencies
  androidTestCompile 'com.android.support.test.espresso:espresso-core:3.0.1'
  androidTestCompile 'com.android.support.test.espresso:espresso-contrib:3.0.1'
  androidTestCompile 'com.android.support.test.espresso:espresso-intents:3.0.1'
  androidTestCompile 'com.android.support.test.espresso:espresso-accessibility:3.0.1'
  androidTestCompile 'com.android.support.test.espresso:espresso-web:3.0.1'
  androidTestCompile 'com.android.support.test.espresso.idling:idling-concurrent:3.0.1'

  // The following Espresso dependency can be either "compile"
  // or "androidTestCompile", depending on your app's implementation
  androidTestCompile 'com.android.support.test.espresso:espresso-idling-resource:3.0.1'
}

2.

android.defaultConfig 添加:

testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

Example Gradle build file

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26

    defaultConfig {
        applicationId "com.my.awesome.app"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
}

dependencies {
    // App's dependencies, including test
    compile 'com.android.support:support-annotations:22.2.0'

    // Testing-only dependencies
    androidTestCompile 'com.android.support.test:runner:1.0.1'
    androidTestCompile 'com.android.support.test.espresso:espresso-core:3.0.1'
}

Add the first test

Android Studio creates tests by default insrc/androidTest/java/com.example.package/.

Example JUnit4 test using Rules:

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

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

    @Test
    public void listGoesOverTheFold() {
        onView(withText("Hello world!")).check(matches(isDisplayed()));
    }
}

Running tests


You can run your tests in Android Studio or from the command line.

In Android Studio

To create a test configuration in Android Studio, complete the following steps:

  1. Open Run > Edit Configurations .
  2. Add a new Android Tests configuration.
  3. Choose a module.
  4. Add a specific instrumentation runner: android.support.test.runner.AndroidJUnitRunner
  5. Run the newly created configuration.

From the command line

Execute the following Gradle command:

./gradlew connectedAndroidTest

results matching ""

    No results matching ""