如何让 Android Studio 不使用 compileOnly 依赖项来运行单元测试?

问题描述

Android Studio (4.1.3) 似乎一直在添加声明为 compileOnly 的依赖项,作为运行单元测试(不是 插装测试)的执行类路径的一部分。

我在一个示例项目中看到了这个,只是让 Android Studio 创建一个新的“基本活动”项目,然后添加任何内容作为 compileOnly 依赖项,运行示例单元测试,并检查命令行由 IDE 使用。依赖项显示在该命令行中。

这对我来说搞砸了,这里的原因并不重要,假设我将某些依赖项声明为“仅编译”是有原因的,我真的不希望它们在我尝试运行时出现。

那么,问题 1 - 这是 Android Studio 中的错误吗?

如果不是(错误),我想我可以理解。原因可能是 - “好吧,您没有在实际设备上运行此代码,因此没有什么可以提供 Android 平台本来会提供的任何类”。这在某些情况下可能很有用,但恕我直言,应该让想要类似内容的人声明与 testImplementation 相同的依赖项,并获得该行为。就我而言,我想关闭它,但不知道如何关闭。另一方面,直接从 Gradle 运行单元测试不使用该类路径,Android Studio 可能应该以相同的方式工作。

那么,问题 2 - 我可以让 Android Studio 不这样做吗,如果是的话 - 怎么做?

示例build.gradle

plugins {
    id 'com.android.application'
}

android {
    compileSdkVersion 29

    defaultConfig {
        applicationId "org.vps.tests.cotest"
        minSdkVersion 28
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'),'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {

    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'com.google.android.material:material:1.3.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
    implementation 'androidx.navigation:navigation-fragment:2.3.3'
    implementation 'androidx.navigation:navigation-ui:2.3.3'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.2'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
    compileOnly 'com.github.houbb:deep-copy-test:0.0.1' // random pick

}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)