AndroidX Test — это набор библиотек Jetpack, позволяющий проводить тесты приложений Android. Он также предоставляет ряд инструментов для написания этих тестов.
Например, AndroidX Test предоставляет правила JUnit4 для запуска действий и взаимодействия с ними в тестах JUnit4. Он также содержит фреймворки для тестирования пользовательского интерфейса, такие как Espresso, UI Automator и симулятор Robolectric.
Добавить тестовые библиотеки AndroidX
Чтобы использовать AndroidX Test, вам необходимо изменить зависимости проекта вашего приложения в среде разработки.
Добавить зависимости Gradle
Чтобы изменить зависимости проекта вашего приложения, выполните следующие действия:
- Шаг 1 : Откройте файл
build.gradle
для вашего модуля Gradle. - Шаг 2 : В разделе репозиториев убедитесь, что отображается репозиторий Maven от Google:
allprojects {
repositories {
jcenter()
google()
}
}
- Шаг 3 : Для каждого тестового пакета AndroidX, который вы хотите использовать, добавьте его имя в раздел зависимостей. Например, чтобы добавить пакет
espresso-core
, добавьте следующие строки:
Круто
dependencies { ... androidTestImplementation "androidx.test.espresso:espresso-core:$espressoVersion" }
Котлин
dependencies { ... androidTestImplementation('androidx.test.espresso:espresso-core:$espressoVersion') }
Ниже приведены наиболее распространённые доступные зависимости AndroidX Test:
Круто
dependencies { // Core library androidTestImplementation "androidx.test:core:$androidXTestVersion0" // AndroidJUnitRunner and JUnit Rules androidTestImplementation "androidx.test:runner:$testRunnerVersion" androidTestImplementation "androidx.test:rules:$testRulesVersion" // Assertions androidTestImplementation "androidx.test.ext:junit:$testJunitVersion" androidTestImplementation "androidx.test.ext:truth:$truthVersion" // Espresso dependencies androidTestImplementation "androidx.test.espresso:espresso-core:$espressoVersion" androidTestImplementation "androidx.test.espresso:espresso-contrib:$espressoVersion" androidTestImplementation "androidx.test.espresso:espresso-intents:$espressoVersion" androidTestImplementation "androidx.test.espresso:espresso-accessibility:$espressoVersion" androidTestImplementation "androidx.test.espresso:espresso-web:$espressoVersion" androidTestImplementation "androidx.test.espresso.idling:idling-concurrent:$espressoVersion" // The following Espresso dependency can be either "implementation", // or "androidTestImplementation", depending on whether you want the // dependency to appear on your APK’"s compile classpath or the test APK // classpath. androidTestImplementation "androidx.test.espresso:espresso-idling-resource:$espressoVersion" }
Котлин
dependencies { // Core library androidTestImplementation("androidx.test:core:$androidXTestVersion") // AndroidJUnitRunner and JUnit Rules androidTestImplementation("androidx.test:runner:$testRunnerVersion") androidTestImplementation("androidx.test:rules:$testRulesVersion") // Assertions androidTestImplementation("androidx.test.ext:junit:$testJunitVersion") androidTestImplementation("androidx.test.ext:truth:$truthVersion") // Espresso dependencies androidTestImplementation( "androidx.test.espresso:espresso-core:$espressoVersion") androidTestImplementation( "androidx.test.espresso:espresso-contrib:$espressoVersion") androidTestImplementation( "androidx.test.espresso:espresso-intents:$espressoVersion") androidTestImplementation( "androidx.test.espresso:espresso-accessibility:$espressoVersion") androidTestImplementation( "androidx.test.espresso:espresso-web:$espressoVersion") androidTestImplementation( "androidx.test.espresso.idling:idling-concurrent:$espressoVersion") // The following Espresso dependency can be either "implementation", // or "androidTestImplementation", depending on whether you want the // dependency to appear on your APK"s compile classpath or the test APK // classpath. androidTestImplementation( "androidx.test.espresso:espresso-idling-resource:$espressoVersion") }
На странице «Заметки о выпуске» содержится таблица с последними версиями каждого артефакта.
Конкретную справочную документацию по этим библиотекам можно найти в Указателе пакетов или Указателе классов .
Проекты, использующие устаревшие классы
Если ваше приложение использует тесты, которые полагаются на устаревшие классы android.test
на основе JUnit3, такие как InstrumentationTestCase
и TestSuiteLoader
, добавьте следующие строки в раздел android
файла:
android {
...
useLibrary 'android.test.runner'
useLibrary 'android.test.base'
useLibrary 'android.test.mock'
}
Добавить декларации манифеста
Для запуска тестов, использующих устаревшие классы android.test
на базе JUnit3, добавьте необходимые элементы <uses-library>
в манифест тестового приложения. Например, если вы добавляете тесты, зависящие от библиотеки android.test.runner
, добавьте в манифест приложения следующий элемент:
<!-- You don't need to include android:required="false" if your app's
minSdkVersion is 28 or higher. -->
<uses-library android:name="android.test.runner"
android:required="false" />
Чтобы определить библиотеку, содержащую заданный класс на основе JUnit, см. раздел Библиотеки на основе JUnit .
Что следует учитывать при использовании устаревших классов и ориентации на Android 9 или
выше
Рекомендации в этом разделе применимы только в том случае, если вы ориентируетесь на Android 9 (уровень API 28) или выше , а минимальная версия SDK для вашего приложения установлена на Android 9.
Библиотека android.test.runner
неявно зависит от библиотек android.test.base
и android.test.mock
. Если ваше приложение использует только классы из android.test.base
или android.test.mock
, вы можете подключить эти библиотеки отдельно:
<!-- For both of these declarations, you don't need to include
android:required="false" if your app's minSdkVersion is 28
or higher. -->
<uses-library android:name="android.test.base"
android:required="false" />
<uses-library android:name="android.test.mock"
android:required="false" />