建立本地单元测试(未注册任何仪器!必须在注册仪器下运行)

maX*_*aXp 7 documentation android unit-testing robolectric

看一下官方文档包括框架依赖项一节提供了有关如何设置本地单元测试以与环境android sdk一起使用的示例。但是,如果您如示例中所述进行所有操作,则测试不会开始。我收到一个错误

java.lang.IllegalStateException:未注册任何工具!必须在注册工具下运行。

所有尝试都是在一个新项目上进行的。Android Studio 3.3,gradle-4.10.1,build:gradle:3.3.0,Kotlin,并包含Androidx工件。

然后将以下行添加到具有指定配置的项目中:

build.gradle

android {
    // ...
    testOptions {
        unitTests.includeAndroidResources = true
    }
}

dependencies {
    // ...
    // Already exist
    testImplementation 'junit:junit:4.12'
    // Added this line
    testImplementation 'androidx.test:core:1.0.0'
}
Run Code Online (Sandbox Code Playgroud)

和测试主体本身:

package com.example.myapplication

import android.content.Context
import androidx.test.core.app.ApplicationProvider
import org.junit.Test

class ExampleUnitTest {

    val context = ApplicationProvider.getApplicationContext<Context>()

    @Test
    fun readStringFromContext_LocalizedString() {
        System.out.println(context.applicationInfo.packageName)
    }
}
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?


apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.example.myapplication"
        minSdkVersion 15
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    testOptions {
        unitTests.includeAndroidResources = true
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.0.0-beta01'
    implementation 'androidx.core:core-ktx:1.1.0-alpha03'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.2'
    testImplementation 'junit:junit:4.12'
    testImplementation 'androidx.test:core:1.0.0'
    androidTestImplementation 'androidx.test:runner:1.1.0-alpha4'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0-alpha4'
}
Run Code Online (Sandbox Code Playgroud)

Vad*_*tov 12

更新

如果您使用的是最新的 gradle 版本,则不应再遇到此错误。


我想您需要在您的build.gradle测试中包含 Robolectric 依赖项,并为您的测试指定测试运行程序:

@RunWith(RobolectricTestRunner.class)
class ExampleUnitTest {
Run Code Online (Sandbox Code Playgroud)

之后它对我有用。我不知道为什么这个信息没有包含在 Android 文档中。

  • 谢谢!最后,我就是这样做的,我也不明白为什么文档中没有包含它。 (7认同)
  • @Jorge 请参阅文档部分:“如果您的测试与多个 Android 框架依赖项交互,或以复杂的方式与这些依赖项交互,请使用 AndroidX Test 提供的 Robolectric 工件”。但是测试运行器注释丢失了,这很奇怪。在这种情况下,我们不是在谈论纯 Junit 测试。我们也不是在谈论仪器测试。 (4认同)