Home:ALL Converter>AndroidX : No instrumentation registered! Must run under a registering instrumentation

AndroidX : No instrumentation registered! Must run under a registering instrumentation

Ask Time:2018-12-03T22:29:35         Author:julioribeiro

Json Formatter

I'm trying to run a local unit test that depends on the context, and was following this guide: https://developer.android.com/training/testing/unit-testing/local-unit-tests#kotlin and I set up my project like this (following this link : https://developer.android.com/training/testing/set-up-project ):

build.gradle(app)

android {
compileSdkVersion 28
buildToolsVersion '27.0.3'
defaultConfig {
    minSdkVersion 21
    targetSdkVersion 27
    versionCode 76
    versionName "2.6.0"
    testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    multiDexEnabled true

useLibrary 'android.test.runner'
    useLibrary 'android.test.base'
    useLibrary 'android.test.mock'

}
testOptions {
    unitTests.returnDefaultValues = true
    unitTests.all {
        // All the usual Gradle options.
        testLogging {
            events "passed", "skipped", "failed", "standardOut", "standardError"
            outputs.upToDateWhen { false }
            showStandardStreams = true
        }
    }
    unitTests.includeAndroidResources = true

}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')

androidTestImplementation("androidx.test.espresso:espresso-core:$espressoVersion", {
    exclude group: 'com.android.support', module: 'support-annotations'
})
// Espresso UI Testing dependencies
implementation "androidx.test.espresso:espresso-idling-resource:$espressoVersion"
androidTestImplementation "androidx.test.espresso:espresso-contrib:$espressoVersion"
androidTestImplementation "androidx.test.espresso:espresso-intents:$espressoVersion"

testImplementation 'androidx.test:core:1.0.0'

// AndroidJUnitRunner and JUnit Rules
androidTestImplementation 'androidx.test:runner:1.1.0'
androidTestImplementation 'androidx.test:rules:1.1.0'
// Espresso Assertions
androidTestImplementation 'androidx.test.ext:junit:1.0.0'
androidTestImplementation 'androidx.test.ext:truth:1.0.0'
androidTestImplementation 'com.google.truth:truth:0.42'
    implementation 'androidx.multidex:multidex:2.0.0'
}

My espresso_version is espressoVersion = '3.1.0'

My test that is located in module-name/src/test/java/ looks like this:

    import android.content.Context
import androidx.test.core.app.ApplicationProvider
import com.instacart.library.truetime.TrueTime
import edu.mira.aula.shared.extensions.android.trueDateNow
import edu.mira.aula.shared.network.ConnectivityHelper
import kotlinx.coroutines.experimental.runBlocking
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import java.util.*
import java.util.concurrent.CountDownLatch

class TimeExtensionsUnitTest {
private lateinit var instrumentationCtx: Context

@Before
fun setup() {
    instrumentationCtx = ApplicationProvider.getApplicationContext<Context>()
}
 @Test
fun testTrueTimeValueReturnsIfInitialized() {
    if (ConnectivityHelper.isOnline(instrumentationCtx)) {
        runBlocking {
            val countDownLatch = CountDownLatch(1)
            TrueTime.build()
                    .withSharedPreferencesCache(instrumentationCtx)
                    .withConnectionTimeout(10000)
                    .initialize()
            countDownLatch.countDown()

            try {
                countDownLatch.await()
                val dateFromTrueTime = trueDateNow()
                val normalDate = Date()
                Assert.assertNotEquals(dateFromTrueTime, normalDate)
            } catch (e: InterruptedException) {
            }
        }
    }
}

Everytime I run it, it gives me:

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)

If I run it as a Instrumental Test(changing the package) it runs without errors. But I thought that this guide was exactly to be able to run unit test using Android Framework classes such as Context. I even tried run that class UnitTestSample but the same error occurs.

I also removed all android.support dependencies from my project

Any ideas on how to solve it?

Author:julioribeiro,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/53595837/androidx-no-instrumentation-registered-must-run-under-a-registering-instrumen
Boris Strandjev :

I had similar error and was struggling a lot to fix it. My problem was that I was mixing AndroidJUnit4, InstrumentationRegistry, ApplicationProvider and AndroidJUnitRunnerversions / packages. Make sure they all are of the same generation. These are the classes that made it all run for me:\n\n\nandroidx.test.runner.AndroidJUnitRunner\nandroidx.test.platform.app.InstrumentationRegistry\nandroidx.test.ext.junit.runners.AndroidJUnit4\nandroidx.test.core.app.ApplicationProvider\n\n\nfor these I needed the following in the dependencies part of my build.gradle\n\nandroidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'\nandroidTestImplementation 'androidx.test:core:1.1.0'\nandroidTestImplementation 'androidx.test.ext:junit:1.1.0'\nandroidTestImplementation \"com.android.support:support-annotations:27.1.1\"\nandroidTestImplementation 'com.android.support.test:runner:1.0.2'\nandroidTestImplementation 'com.android.support.test:rules:1.0.2'\n\n\nAnd of course the correct\n\ntestInstrumentationRunner \"androidx.test.runner.AndroidJUnitRunner\"\n\n\nin my defaultConfig of the build.gradle",
2019-02-28T16:42:37
McBodik :

Next things are not mentioned on google test guide, but they are what I found:\n\nandroidx.test in case of unit tests is just an interface/api (I don't know what about instrumented tests) and it needs implementations, which is robolectric library.\nThat's why robolectric dependency is also required:\ntestImplementation "org.robolectric:robolectric:{version}"\n@RunWith(AndroidJUnit4.class)\nis required. To get nondeprecated class you need to add:\ntestImplementation "androidx.test.ext:junit:{version}". By the way this dependency has transitive junit4 dependensy.\n\nAlso you can faced with: Failed to create a Robolectric sandbox: Android SDK 29 requires Java 9 (have Java 8) in case you use java 8 and compileSdkVersion 29 or above. Here you can find how to deal with it.",
2020-10-09T21:13:24
André Ramon :

Make sure to put your instrumentation tests (tests you run with a Runner) in androidTest and not just test",
2021-04-22T18:21:45
Sana Ebadi :

in my case I was using getApplicationContext() in a fragment from the test package, I just change it to getContext(). and this fixed my crash!",
2022-08-13T12:56:05
Mesut GUNES :

In my case, changing the test method name fixed the issue.\nMost probably the Android Studio cached the methods with indexes that caused a problem.",
2021-03-02T20:06:03
ruhulamin choudhury :

[Note : To remember this ]\nAndroidJUnit4.class | used to run testcases of intrumentation type inside source set called androidTest [which requires phone or emulator]\nAndroidJUnit4ClassRunner | used to run testcases for local test inside source set called test folder. [ no phone /emulator required]\nException or Improvement Case | Using Robo-electric and supported junit4 dependency, then AndroidJUnit4.class can be used inside test folder to test local test.\nUse this dependency[try to add latest]\ntestImplementation "org.robolectric:robolectric:4.4"\nThen in your test class, use @RunWith(AndroidJUnit4::class)\nExample : @RunWith(AndroidJUnit4::class)\n-------For Reference-----\n@RunWith(AndroidJUnit4::class)\nclass TasksViewModelTest {\n@Test\nfun addNewTask_setsNewTaskEvent() {\n\n // Given a fresh TasksViewModel\n var tasksViewModel = TasksViewModel(ApplicationProvider.getApplicationContext())\n\n // When adding a new task\n tasksViewModel.addNewTask()\n\n // Then the new task event is triggered\n\n}\n\n}",
2022-07-20T11:31:32
qix :

Looks like you forgot to annotate your TimeExtensionsUnitTest with @RunWith(AndroidJUnit4::class) re: https://github.com/android/android-test/issues/409. I can reproduce the error by commenting that out in my own tests.\nThat said, this is not the only way to get your error. I originally encountered it when I was updating some old Robolectric tests to use some AndroidX apis (http://robolectric.org/androidx_test/), including switching away from @RunWith(RobolectricTestRunner::class). In my case, I was trying to use a context in my @BeforeClass with ApplicationProvider.getApplicationContext<Context>(), which is wrong in AndroidX, even though it was ok using Roboletric's runner with appContext = RuntimeEnvironment.getApplication().applicationContextappContext. Fortunately I was able to move the logic into my @Before call to fix things without a significant hit.\nMore generally, I've noticed documentation out there isn't fully comprehensive all in one place explaining the migration from the very old android.support.test Android Testing Support Library and Roboletric dependencies to AndroidX, but here's some other notes:\n\nIf I want to run real instrumentation tests on an emulator/physical device, ensure that the tests are under src/androidTest. This also means I need to change in my build.gradle file the dependencies on androidx.test libraries from testImplementation => androidTestImplementation, and also explicitly set a testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" in the defaultConfig section.\nhttps://developer.android.com/training/testing/local-tests\nhttps://developer.android.com/training/testing/instrumented-tests\nIf I'm happy with using Robolectric to run those tests as local, I can keep them under src/test, declare the dependencies using testImplementation, and don't need the testInstrumentationRunner. It's nice that I don't have to change the code to do this since I'm using the AndroidX Test APIs, which Roboletric is compatible with as of v4.0.\n",
2022-08-25T07:38:10
Archie G. Quiñones :

Update\n\nYou should no longer encounter this error if youre using the latest gradle version.\n\n\n\nI also encountered this issue.\n\nIf you look at migrating to Robolectric 4.0 here, it suggest to add the following line in your gradle.properties.\n\nandroid.enableUnitTestBinaryResources=true\n\n\nThe problem is that, if you add this you your gradle.properties, it will output this warning: \n\n\n WARNING: The option setting\n 'android.enableUnitTestBinaryResources=true' is experimental and\n unsupported.\n\n\nNow, if you look at Robolectric releases here. You could see that this is a known issue where they state that\n\n\n Android Gradle Plugin may report the following warning, which may be safely ignored: WARNING: The option setting 'android.enableUnitTestBinaryResources=true' is experimental and unsupported.. Android Gradle Plugin 3.4 will resolve this issue.\n\n\nI believe unless you could update you gradle to 3.4. You won't be able to solve this issue.\n\nWhat I did instead was to include Robolectric 4.0 as dependency.\n\ntestImplementation \"org.robolectric:robolectric:4.0.2\"\n\n\nand annotate my test class with \n\n@RunWith(RobolectricTestRunner::class)\n\n\nThis should make your test work.\n\nNow when you run the test, you'll notice that Robolectric will log the following:\n\n\n [Robolectric] NOTICE: legacy resources mode is deprecated; see\n http://robolectric.org/migrating/#migrating-to-40\n\n\nIgnore this for now but as soon as you could update your gradle, migrate to the new Robolectric testing.",
2018-12-10T03:00:02
Patrick :

I got the same problem and here is how i fixed it:\n\nmove my test class to the "androidTest" package\nannotate the test class with @RunWith(AndroidJUnit4.class)\n\nHope this can help",
2022-09-12T07:53:35
crazygit :

I follow the official guide also met this issue, fix it with below steps.\nAdd testImplementation in app build.gradle\n// Required -- JUnit 4 framework\ntestImplementation 'junit:junit:4.13.1'\n\ntestImplementation 'androidx.test:core-ktx:1.3.0'\ntestImplementation 'androidx.test.ext:junit-ktx:1.1.2'\n\n// Robolectric environment\ntestImplementation 'org.robolectric:robolectric:4.4'\n\n// Optional -- truth\ntestImplementation 'androidx.test.ext:truth:1.3.0'\ntestImplementation 'com.google.truth:truth:1.0'\n\n// Optional -- Mockito framework\ntestImplementation 'org.mockito:mockito-core:3.3.3'\n\nThe official guide missed two testImplementations\ntestImplementation 'androidx.test.ext:junit-ktx:1.1.2'\n\ntestImplementation 'org.robolectric:robolectric:4.4'\n\nAdd testOptions block in app build.gradle\n android {\n // ...\n testOptions {\n unitTests.includeAndroidResources = true\n }\n }\n\nAdd @RunWith(AndroidJUnit4::class) to your test class\nExample:\nimport android.content.Context\nimport android.os.Build.VERSION_CODES.Q\nimport androidx.test.core.app.ApplicationProvider\nimport androidx.test.ext.junit.runners.AndroidJUnit4\nimport com.google.common.truth.Truth.assertThat\nimport org.junit.Test\nimport org.junit.runner.RunWith\nimport org.robolectric.annotation.Config\n\n@RunWith(AndroidJUnit4::class)\n@Config(sdk = [Q])\nclass UnitTestWithContextDemoTest {\n\n private val context: Context = ApplicationProvider.getApplicationContext()\n \n fun test_getPackageName() {\n assertThat(context.packageName).contains("your_package_name")\n }\n}\n\nNOTE\n@Config(sdk = [Q]) is required when your targetSdkVersion greater than 29. Because robolectric NOT support targetSdkVersion greater than 29.",
2020-11-25T13:48:19
HotJard :

Spend hours on similar issue, and the problem wasn't in dependencies, rather in AndroidStudio itself Based on the answer: \n\nIDE tries to run local unit tests instead of instrumented\n\n.\n\nMake sure it's run as instrumented test (red is local tests, green - instrumented):\n\n\n\nAfter added instrumented test for the class it's run as expected under instrumented. How I done this? 2 ways I found: \n\n1) Edit configuration (as on the last screenshot) and adding function manually\n\n2) Under Project tap (top left corner) I selected Tests instead of android, found the test, right click - create test. After this step all new tests are run under instrumented tests",
2019-12-13T10:17:58
yy