Set different minSdkVersion for testAndroid than for main app

Is it possible to set a different minSdkVersion for tests than for the app itself? I ask because I want to use the new Test Support Library and UI Automator for testing. However, this is only available on API 18+. At the same time, I still want to support older versions of Android, albeit not as thoroughly tested. What do I need to add to my build.gradle file in order to do this?

To clarify, I am using Android Studio and the "new" Gradle-based project structure.


I got this from the new testing template from Google.

Create a new AndroidManifest.xml file in your test or androidTest folder.

<?xml version="1.0" encoding="utf-8"?>
<manifest
    xmlns:tools="http://schemas.android.com/tools"
    package="your.package.name">

    <uses-sdk tools:overrideLibrary="android.support.test.uiautomator.v18"/>
</manifest>

try this one.

defaultConfig {
    applicationId "com.test"
    if (gradle.startParameter.taskNames.contains(":app:assembleDebug")) {
        minSdkVersion 21
    }else{
        minSdkVersion 14
    }
    targetSdkVersion 22
    versionCode Integer.parseInt(VERSION_CODE)
    versionName VERSION_NAME
}



updated 2020-04-16


You can also set with productFlavors

android {
    compileSdkVersion 29

    defaultConfig {
        applicationId "com.test"
        targetSdkVersion 29
        versionCode 1
        versionName "1.0.0"
    }

    buildTypes {
        debug {
        }
        release {
            minifyEnabled true
        }
    }

    flavorDimensions "default"

    productFlavors {
        development {
            minSdkVersion 21
        }
        production {
            minSdkVersion 16
        }
    }
}