29

我尝试通过“gradlew connectedAndroidTest”运行仪器测试。我收到以下错误:

Tests on GT-I9305 - 4.3 failed: Instrumentation run failed due to 'java.lang.ClassNotFoundException'

com.android.builder.testing.ConnectedDevice > hasTests[GT-I9305 - 4.3] FAILED 
No tests found.                              
:mobile:connectedAndroidTest FAILED 

这是带有 --stacktrace 选项的输出:

org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':mobile:connectedAndroidTest'.
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:69)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:46)
        at org.gradle.api.internal.tasks.execution.PostExecutionAnalysisTaskExecuter.execute(PostExecutionAnalysisTaskExecuter.java:35)
        at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:64)
        at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
        at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:42)
        at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
        at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:53)
        at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
        at org.gradle.api.internal.AbstractTask.executeWithoutThrowingTaskFailure(AbstractTask.java:305)
        at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.executeTask(AbstractTaskPlanExecutor.java:79)
        at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.processTask(AbstractTaskPlanExecutor.java:63)
        at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.run(AbstractTaskPlanExecutor.java:51)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor.process(DefaultTaskPlanExecutor.java:23)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:88)
        at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:29)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:62)
        at org.gradle.execution.DefaultBuildExecuter.access$200(DefaultBuildExecuter.java:23)
        at org.gradle.execution.DefaultBuildExecuter$2.proceed(DefaultBuildExecuter.java:68)
        at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:32)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:62)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:55)
        at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:149)
        at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:106)
        at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:86)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter$DefaultBuildController.run(InProcessBuildActionExecuter.java:80)
        at org.gradle.launcher.cli.ExecuteBuildAction.run(ExecuteBuildAction.java:33)
        at org.gradle.launcher.cli.ExecuteBuildAction.run(ExecuteBuildAction.java:24)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:36)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:26)
        at org.gradle.launcher.cli.RunBuildAction.run(RunBuildAction.java:51)
        at org.gradle.internal.Actions$RunnableActionAdapter.execute(Actions.java:171)
        at org.gradle.launcher.cli.CommandLineActionFactory$ParseAndBuildAction.execute(CommandLineActionFactory.java:237)
        at org.gradle.launcher.cli.CommandLineActionFactory$ParseAndBuildAction.execute(CommandLineActionFactory.java:210)
        at org.gradle.launcher.cli.JavaRuntimeValidationAction.execute(JavaRuntimeValidationAction.java:35)
        at org.gradle.launcher.cli.JavaRuntimeValidationAction.execute(JavaRuntimeValidationAction.java:24)
        at org.gradle.launcher.cli.CommandLineActionFactory$WithLogging.execute(CommandLineActionFactory.java:206)
        at org.gradle.launcher.cli.CommandLineActionFactory$WithLogging.execute(CommandLineActionFactory.java:169)
        at org.gradle.launcher.cli.ExceptionReportingAction.execute(ExceptionReportingAction.java:33)
        at org.gradle.launcher.cli.ExceptionReportingAction.execute(ExceptionReportingAction.java:22)
        at org.gradle.launcher.Main.doAction(Main.java:33)
        at org.gradle.launcher.bootstrap.EntryPoint.run(EntryPoint.java:45)
        at org.gradle.launcher.bootstrap.ProcessBootstrap.runNoExit(ProcessBootstrap.java:54)
        at org.gradle.launcher.bootstrap.ProcessBootstrap.run(ProcessBootstrap.java:35)
        at org.gradle.launcher.GradleMain.main(GradleMain.java:23)
        at org.gradle.wrapper.BootstrapMainStarter.start(BootstrapMainStarter.java:33)
        at org.gradle.wrapper.WrapperExecutor.execute(WrapperExecutor.java:130)
        at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:48)
Caused by: org.gradle.api.GradleException: There were failing tests. See the report at: file:///D:/myapp/mobile/build/outputs/reports/androidTests/connected/index.html
        at com.android.build.gradle.internal.tasks.DeviceProviderInstrumentTestTask.runTests(DeviceProviderInstrumentTestTask.groovy:92)
        at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:63)
        at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.doExecute(AnnotationProcessingTaskFactory.java:218)
        at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.java:211)
        at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.java:200)
        at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:579)
        at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:562)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:80)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:61)
        ... 47 more

我的AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapp" >

    <instrumentation
        android:targetPackage="com.example.myapp"
        android:name="android.test.InstrumentationTestRunner" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme"
        android:name="com.example.myapp.MyApplication">
        <activity
            android:name="com.example.myapp.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <uses-library android:name="android.test.runner" />
    </application>

</manifest>

我的build.gradle

apply plugin: 'com.android.application'
apply plugin: 'com.neenbedankt.android-apt'
apply plugin: 'robolectric'

android {
    compileSdkVersion 21
    buildToolsVersion "20.0.0"

    defaultConfig {
        applicationId "com.example.myapp"
        minSdkVersion 18
        targetSdkVersion 21
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "com.google.android.apps.common.testing.testrunner.GoogleInstrumentationTestRunner"
    }
    buildTypes {
        release {
            runProguard false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    sourceSets {
        androidTest {
            setRoot('src/androidTest')
        }
        test {
            setRoot('src/test')
        }
    }
}

android {
    packagingOptions {
        exclude 'META-INF/LICENSE.txt'
        exclude 'LICENSE.txt'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/NOTICE'
    }
}
configurations {
    apt
}

apt {
    arguments {
        resourcePackageName android.defaultConfig.packageName
        androidManifestFile variant.outputs[0].processResources.manifestFile
    }
}

ext {
    daggerVersion = '1.2.2';
    androidAnnotationsVersion = '3.2';
    robobindingVersion = '0.8.9';
    jodatimeVersion = '2.5.1';
    ormliteVersion = '4.48';
    ottoVersion = '1.3.5';
    commonsioVersion = '2.0.1';
    playservicesVersion = '6.1.71';
    supportv4Version = '21.0.2';
    javaxinjectVersion = '1';
    junitVersion = '4.11';
    robolectricVersion = '2.4';
}

dependencies {
    androidTestCompile files('lib/espresso-1.1.jar', 'lib/testrunner-1.1.jar', 'lib/testrunner-runtime-1.1.jar')
    androidTestCompile 'com.google.guava:guava:14.0.1'
    androidTestCompile 'com.squareup.dagger:dagger:1.2.2'
    androidTestCompile 'org.hamcrest:hamcrest-integration:1.1'
    androidTestCompile 'org.hamcrest:hamcrest-core:1.1'
    androidTestCompile 'org.hamcrest:hamcrest-library:1.1'

    androidTestCompile("junit:junit:${junitVersion}") {
        exclude module: 'hamcrest-core'
    }
    androidTestCompile("org.robolectric:robolectric:${robolectricVersion}") {
        exclude module: 'classworlds'
        exclude module: 'commons-logging'
        exclude module: 'httpclient'
        exclude module: 'maven-artifact'
        exclude module: 'maven-artifact-manager'
        exclude module: 'maven-error-diagnostics'
        exclude module: 'maven-model'
        exclude module: 'maven-project'
        exclude module: 'maven-settings'
        exclude module: 'plexus-container-default'
        exclude module: 'plexus-interpolation'
        exclude module: 'plexus-utils'
        exclude module: 'wagon-file'
        exclude module: 'wagon-http-lightweight'
        exclude module: 'wagon-provider-api'
    }

    androidTestCompile 'com.squareup:fest-android:1.0.+'

    apt "org.robobinding:codegen:$robobindingVersion"
    compile("org.robobinding:robobinding:$robobindingVersion:with-dependencies") {
        exclude group: 'com.google.guava', module: 'guava'
    }
    apt "org.androidannotations:androidannotations:${androidAnnotationsVersion}"
    compile "org.androidannotations:androidannotations-api:${androidAnnotationsVersion}"
    apt "com.squareup.dagger:dagger-compiler:${daggerVersion}"
    compile "com.squareup.dagger:dagger:${daggerVersion}"
    compile fileTree(dir: 'libs', include: ['*.jar'])
    wearApp project(':wear')
    compile project(':javamail')
    compile "com.google.android.gms:play-services:${playservicesVersion}"
    compile "com.android.support:support-v4:${supportv4Version}"
    compile "com.squareup:otto:${ottoVersion}"
    compile "javax.inject:javax.inject:${javaxinjectVersion}"
    compile "com.j256.ormlite:ormlite-core:${ormliteVersion}"
    compile "com.j256.ormlite:ormlite-android:${ormliteVersion}"
    compile group: 'commons-io', name: 'commons-io', version: "${commonsioVersion}"
    compile "net.danlew:android.joda:${jodatimeVersion}"
}

apply plugin: 'idea'
idea {
    module {
        testOutputDir = file('build/test-classes/debug')
    }
}


android.applicationVariants.all { variant ->
    def aptOutput = file("${project.buildDir}/generated/source/apt/${variant.dirName}")
    println "****************************"
    println "variant: ${variant.name}"
    println "manifest:  ${variant.processResources.manifestFile}"
    println "aptOutput:  ${aptOutput}"
    println "****************************"

    variant.javaCompile.doFirst {
        println "*** compile doFirst ${variant.name}"
        aptOutput.mkdirs()
        variant.javaCompile.options.compilerArgs += [
                '-processorpath', configurations.apt.getAsPath(),
                '-AandroidManifestFile=' + variant.processResources.manifestFile,
                '-s', aptOutput
        ]
    }
}

我的测试课

public class MainActivityTest extends ActivityInstrumentationTestCase2<MainActivity> {

    public MainActivityTest() {
        super(MainActivity.class);
    }

    public void testSomething() {
        assertTrue(true);
    }

}    

任何想法?

4

7 回答 7

22

我刚刚发现自己遇到了同样的问题,并通过更新到 espresso 2.0 解决了这个问题

替换 build.gradle 文件中的 testInstrumentationRunner

 testInstrumentationRunner "com.google.android.apps.common.testing.testrunner.GoogleInstrumentationTestRunner

testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

并将新的依赖项更新为 2.0

androidTestCompile files('lib/espresso-1.1.jar', 'lib/testrunner-1.1.jar', 'lib/testrunner-runtime-1.1.jar')

androidTestCompile 'com.android.support.test:testing-support-lib:0.1'
androidTestCompile 'com.android.support.test.espresso:espresso-core:2.0'

您还必须更改测试中的命名空间,但在运行它们时您会注意到。

完整说明: https ://code.google.com/p/android-test-kit/wiki/EspressoSetupInstructions

编辑:

似乎我回答得太早了,我发布的答案只在 5.0 设备上修复了它。以下是在旧设备上修复它的内容:

通过更改将 javax.inject 从新依赖项中排除:

androidTestCompile 'com.android.support.test.espresso:espresso-core:2.0'

androidTestCompile('com.android.support.test.espresso:espresso-core:2.0') {
    exclude group: 'javax.inject'
}

来源: 运行 Espresso 测试时出现 NoClassDefFoundError 的 Dagger 代码,正常运行正常

于 2015-01-14T16:51:05.470 回答
6

当我在Kotlin中编写测试并在方法名称中使用空格时,我遇到了这个问题。它崩溃并显示错误消息: java.lang.ClassNotFoundException: Didn't find class "android.support.test.runner.AndroidJUnitRunner"

在 Android Studio 中: No tests where found

损坏的测试: 方法名称中的空格,在 Android 上不起作用

class RandomTest {

    @Test
    fun `do not use spaces it will not work on Android devices or emulators`() {
        assertThat(2 + 2).isEqualTo(4)
    }
}

解决方法: 去掉空格,一切正常编译

class RandomTest {

    @Test
    fun write_method_names_java6_compatible_without_spaces() {
        assertThat(2 + 2).isEqualTo(4)
    }
}

这可能是因为我禁用了检查“Illegal Android Identifier”,所以在编写 JVM 测试时它不会让我烦恼

于 2017-01-13T11:06:06.993 回答
4

我的问题是在 Kotlin 中添加测试,但之前没有 Kotlin 支持。所以我需要输入我的gradle:

apply plugin: 'kotlin-android'

然后删除测试配置并重新添加。

于 2019-04-16T04:44:48.573 回答
2

经过一些重构后,我尝试从控制台运行测试时遇到了这个问题。

解决方案是修复 AndroidManifest.xml,因为它包含对不再存在的活动和其他类的引用。

当然,该项目将使用错误的清单进行编译,但是当您尝试运行它时,设备将找不到定义的类。因此 ClassNotFoundException。

于 2015-01-28T19:50:24.940 回答
2

从Original Answer复制答案。

这是我在项目中注意到的,在我的 app(main) 模块 build.gradle 中,我有以下 buildType 配置

buildTypes {
        debug {
            multiDexEnabled true
        }

        mock {
            initWith(buildTypes.debug)
        }
    }
testBuildType "mock"

当我使用AndroidJUnitRunner作为测试运行程序(都来自 Android Studio)和build.gradle中的 testInstrumentationRunner 时,测试运行顺利。

在将multiDexEnabled true作为defaultConfig的子模块中

defaultConfig {
    multiDexEnabled true
    ....
}

我遇到了问题

Test running startedTest running failed: Unable to find instrumentation info for:{mypackage.x.y/android.support.test.runner.AndroidJUnitRunner"}

当我在 IDE 和子模块 build.gradle 中指定AndroidJUnitRunner时。通过在 IDE/build.gradle 中将 MultiDexTestRunner 指定为测试运行程序来解决此问题。

总而言之,当 build.gradle 中指定multiDexEnabled true时,使用MultiDexTestRunner运行测试,否则使用AndroidJUnitRunner作为测试运行器。

于 2016-11-24T10:27:03.137 回答
2

我遇到过类似的问题。在我的项目中,有多个模块并启用了 multidex。对我来说,问题在于缺少一个特定的模块 multidex 启用选项(multiDexEnabled true)。

在主模块(app)中,build.gradle 如下所示:

...
multiDexEnabled true
testInstrumentationRunner "com.android.test.runner.MultiDexTestRunner"
...

在另一个模块(应用程序所依赖的)中,build.gradle 缺少“multiDexEnabled true”行。添加此行解决了该问题。

于 2016-11-21T14:19:41.680 回答
0

我通过关闭 Proguard 解决了这个问题。

于 2018-10-14T11:25:16.603 回答