Android项目如何只在单元测试时引入特定libs/jar/aar

正常情况下Android项目需要的jar包,我们可以通过放置到项目对应的libs目录下即可。但是如果我们只希望某些特定libs/jar/aar只在执行单元测试时引入,那么应该怎么处理呢?

Android Studio 4.1.x及以上版本,build tools 4.1.x及以上版本的情况下(较低的版本可能不支持这些配置项),我们可以通过使用 androidTestImplementation fileTree的方式进行引入(同理 常规单元测试使用 testImplementation fileTree),如下:

apply plugin: 'android'

dependencies {
    implementation project(':android-sdk')

    // The libs folder is included in the apk of the real app
    Implementation fileTree(dir: 'libs', include: '*.jar')

    // The tests-libs folder is included only for tests
    androidTestImplementation fileTree(dir: 'libs-tests', include: '*.jar')
}


android {
    compileSdkVersion 19
    buildToolsVersion "20.0.0"

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7
    }


    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            java.srcDirs = ['src']
            resources.srcDirs = ['src']
            aidl.srcDirs = ['src']
            renderscript.srcDirs = ['src']
            res.srcDirs = ['res']
            assets.srcDirs = ['assets']
        }

        // Move the tests to tests/java, tests/res, etc...
        androidTest.setRoot('tests')

        // Note - to run the tests from command line:
        // $ gradle clean connectedCheck build
        // (requires gradle 1.10)

        // Move the build types to build-types/<type>
        // For instance, build-types/debug/java, build-types/debug/AndroidManifest.xml, ...
        // This moves them out of them default location under src/<type>/... which would
        // conflict with src/ being used by the main source set.
        // Adding new build types or product flavors should be accompanied
        // by a similar customization.
        debug.setRoot('build-types/debug')
        release.setRoot('build-types/release')
    }
}

参考链接


发布者

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注