androidgradlegradle-pluginsource-setsandroid-sourcesets

How to separate source files per test type in an Android library project?


I was following the gradle docs to separate source files per test type in a Java project and I wanted to do the same thing in an Android library project. By default Android plugin com.android.library supports two types of test directories test and androidTest. How do I add say integTest which I wanted to run after test?

sourceSets {
     integTest {
         java.srcDir file('src/integTest/java')
         resources.srcDir file('src/integTest/resources')
     }
}

When I try to add the above sourceSet to the build.gradle, I get the error

ERROR: The SourceSet 'integTest' is not recognized by the Android Gradle Plugin. Perhaps you misspelled something?

Since Android Gradle Plugin doesn't support custom sourceSets like Java Plugin, is there any other way to solve this problem?


Solution

  • The main reason for the error is defining the sourceSet for integTest inside android, just moving it outside solved the issue. See below for correct build.gradle

    apply plugin: 'com.android.library'
    
    android {
        compileSdkVersion 28
    
    
    
        defaultConfig {
            minSdkVersion 23
            targetSdkVersion 28
            versionCode 1
            versionName "1.0"
    
            testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    
        }
    
        buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
            }
        }
    
    }
    
    sourceSets {
        integTest {
            java.srcDir file('src/integTest/java')
            resources.srcDir file('src/integTest/resources')
        }
    }
    
    configurations {
        integTestCompile.extendsFrom testCompile
        integTestRuntime.extendsFrom testRuntime
    }
    
    task integTest(type: Test) {
        group = LifecycleBasePlugin.VERIFICATION_GROUP
        description = 'Runs the integration tests.'
        testClassesDirs = sourceSets.integTest.output.classesDirs
        classpath = sourceSets.integTest.runtimeClasspath
    }
    
    check.dependsOn integTest
    
    dependencies {
        implementation fileTree(dir: 'libs', include: ['*.jar'])
    
        implementation 'com.android.support:appcompat-v7:28.0.0'
        testImplementation 'junit:junit:4.12'
        integTestImplementation 'junit:junit:4.12'
        androidTestImplementation 'com.android.support.test:runner:1.0.2'
        androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    }