请查看官方文档。章节"包含框架依赖项"给出了如何设置本地单元测试以与环境android sdk一起工作的示例。但是,如果您按照示例的步骤进行操作,则测试不会启动,而是会出现以下错误:
java.lang.IllegalStateException: No instrumentation registered! Must run under a registering instrumentation.
我已经尝试在一个新项目上执行了所有操作。使用的是Android Studio 3.3、gradle-4.10.1、build:gradle:3.3.0、Kotlin和包括Androidx artifacts。
然后将以下行添加到具有指定配置的项目中:
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'
}
还有测试主体本身:
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)
}
}
我做错了什么吗?
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'
}