AndroidX Test – это набор библиотек Jetpack, которые позволяют тестировать приложения Android. В нем также есть ряд инструментов, которые помогут вам писать эти тесты.
Например, AndroidX Test предоставляет правила JUnit4 для запуска объектов activity и взаимодействия с ними в тестах JUnit4. Также в него входят фреймворки для тестирования интерфейса, такие как Espresso, UI Automator и симулятор Robolectric.
Как добавить библиотеки AndroidX Test
Чтобы использовать AndroidX Test, необходимо изменить зависимости проекта приложения в среде разработки.
Как добавить зависимости Gradle
Чтобы изменить зависимости проекта приложения, выполните следующие действия:
- Шаг 1. Откройте файл
build.gradleдля модуля Gradle. - Шаг 2. В разделе репозиториев убедитесь, что указан репозиторий Google Maven:
allprojects {
repositories {
jcenter()
google()
}
}
- Шаг 3. Для каждого пакета AndroidX Test, который вы хотите использовать, добавьте его название в раздел dependencies. Например, чтобы добавить пакет
espresso-core, добавьте следующие строки:
Яркий
dependencies { ... androidTestImplementation "androidx.test.espresso:espresso-core:$espressoVersion" }
Kotlin
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" }
Kotlin
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") }
На странице Примечания к выпуску есть таблица с последними версиями артефактов.
Чтобы найти справочную документацию по этим библиотекам, перейдите к индексу пакетов или индексу классов.
Проекты, в которых используются устаревшие классы
Если в вашем приложении используются тесты, основанные на устаревших классах JUnit3 android.test, например 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" />