androidx.test.InstrumentationRegistry устарел - программирование
Подтвердить что ты не робот

androidx.test.InstrumentationRegistry устарел

переключился на AndroidX и получил устаревшее: import androidx.test.InstrumentationRegistry

если я сделал следующий импорт: import androidx.test.platform.app.InstrumentationRegistry я не могу getContext()

ex: val context = InstrumentationRegistry.getContext()

В build.gradle:

androidTestImplementation 'androidx.test.ext:junit:1.0.0-beta02'
androidTestImplementation 'androidx.test:runner:1.1.0-beta02'
4b9b3361

Ответ 1

Вы можете использовать InstrumentationRegistry.getInstrumentation().getTargetContext() в большинстве случаев из androidx.test.platform.app.InstrumentationRegistry.

Если вам нужно приложение, вы можете использовать ApplicationProvider.getApplicationContext<MyAppClass>()

если у вас его еще нет, я думаю, что у вас также есть новая тестовая зависимость: androidTestImplementation 'androidx.test:core:1.0.0-beta02'

Ответ 2

Когда вы используете Android X, вам нужно убедиться, что в файле вашего приложения build.gradle есть следующее

androidTestImplementation 'androidx.test:core:1.1.0'
androidTestImplementation 'androidx.test.ext:junit:1.1.0'

Во-вторых, убедитесь, что у вас есть правильный AndroidJUnit4 для использования в ваших тестах.

Убедитесь, что вы импортируете оба из них.

import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4

Теперь вместо использования val context = InstrumentationRegistry.getContext() вы можете использовать строку, показанную ниже

val context = InstrumentationRegistry.getInstrumentation().getTargetContext()

Ответ 3

Для использования Kotlin, чтобы получить Контекст:

InstrumentationRegistry.getInstrumentation().targetContext

Ответ 4

InstrumentationRegistry.getInstrumentation().targetContext устарел. Используйте ApplicationProvider.getApplicationContext(); ,

Ответ 5

Я потратил много времени на перемещение зависимости с testImplementation вместо androidTestImplementation и наоборот, в приложении build.gradle.

Моя ошибка была в том, что я создал тестовый класс в папке test вместо папки androidTest, поэтому получаю неразрешенную ошибку для AndroidJuit4 и InstrumentationRegistry.

Когда я переместил свой тестовый файл в папку androidTest, проблема была решена с помощью независимой реализации тестовых библиотек с androidTestImplementation в build.gradle.