Я пишу очень простой локальный модульный тест, чтобы получить контекст приложения и прочитать строку, используя это. Наша цель состоит в модульном тестировании API-клиента и интерфейса, которые мы написали, для выполнения вызова API с использованием модернизации 2x.
Добавлены следующие зависимости в файл build.gradle
Build.gradle:
defaultConfig {
applicationId "x"
minSdkVersion 23
targetSdkVersion 28
versionCode 89
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.2.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
androidTestImplementation 'androidx.test:rules:1.3.0-alpha02'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.annotation:annotation:1.1.0'
testImplementation 'com.squareup.okhttp3:mockwebserver:3.2.0'
testImplementation 'androidx.test:core:1.2.0'
Класс локальных модульных тестов:
import android.content.Context
import androidx.test.core.app.ApplicationProvider
import org.junit.Test
class ExampleAPITest {
@Test
fun useAppContext() {
// val context: Context = InstrumentationRegistry.getInstrumentation().targetContext
val context: Context = ApplicationProvider.getApplicationContext<Context>()
val appName = context.getString(R.string.app_name)
println(appName)
}
}
Мы используем Espresso для автоматизации тестирования. Таким образом, у нас есть обе зависимости, добавленные в файл Gradle. Мы получаем ниже исключения во время выполнения локального модульного теста класса ExampleUnitTest,
java.lang.IllegalStateException: No instrumentation registered! Must run under a registering instrumentation.
at androidx.test.platform.app.InstrumentationRegistry.getInstrumentation(InstrumentationRegistry.java:45)
at androidx.test.core.app.ApplicationProvider.getApplicationContext(ApplicationProvider.java:41)
at com.trimble.cec.appname.ExampleAPITest.loginApiTest(ExampleAPITest.kt:19)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Я знаю, что мы можем использовать mockito или Robolectric для насмешки / доступа к платформе Android, нам нужен только контекст для вызова службы API. В любом случае мы будем автоматизировать вызов API как часть Android Test. Нам нужно создать локальный тест для локального тестирования вызовов API.
Мы написали наш тест Android с использованием Java и локальный модульный тест с использованием Kotlin.
Просматривал исключение выше и пробовал разные версии зависимостей, но ничего не помогает. Похоже, это проблема ядра библиотеки тестирования поддержки Android. Может кто-нибудь помочь мне избавиться от этой проблемы. Спасибо!