问题 运行 测试(<androidx.test.ext.junit.runners.AndroidJUnit4> 没有零参数构造函数)

Problems running tests (<androidx.test.ext.junit.runners.AndroidJUnit4> has no zero argument constructor)

最近我将我的 JUnit 4 runner 从 androidx.test.runner.AndroidJUnit4 升级到 androidx.test.ext.junit.runners.AndroidJUnit4。

当我执行测试时出现以下错误:测试 运行 失败:

Instrumentation run failed due to 'Process crashed.'

LogCat 显示此错误:

java.lang.InstantiationException: 
java.lang.Class<androidx.test.ext.junit.runners.AndroidJUnit4> has no zero argument constructor

测试中的所有导入都是正确的,我在构建中没有遇到任何错误。

我的应用 gradle 看起来像这样:

defaultConfig {
        testInstrumentationRunner 'androidx.test.ext.junit.runners.AndroidJUnit4'
    }

implementation fileTree(include: ['*.jar'], dir: 'libs')
    androidTestImplementation "androidx.test.ext:junit:1.1.0"
    androidTestImplementation 'androidx.test:rules:1.1.1'
    androidTestImplementation 'androidx.test:runner:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-intents:3.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'

尝试

testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"

代替

testInstrumentationRunner 'androidx.test.ext.junit.runners.AndroidJUnit4'

将此行添加到模块的 build.gradle 文件中:

androidTestImplementation 'androidx.test.ext:junit:<version>'

当我导入以下代码时:

import org.junit.Test;

它解决了我的错误。