Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy debug assets for unit tests

I have an android library gradle project. And I need to copy some files to assets folder for robolectric unit tests.

To do it I've defined a copy task:

task copyDebugAssets(type: Copy)  {
    from "${projectDir}/somewhere"
    into "${buildDir}/intermediates/bundles/debug/assets"
}

but I can't add this task as a dependency for processDebugResources task:

processDebugResources.dependsOn copyDebugAssets

because of this error:

Could not get unknown property 'processDebugResources' for object of type com.android.build.gradle.LibraryExtension.

Now I have to manually execute this task before unit test:

./gradlew clean copyDebugAssets test

How can I solve it?

like image 458
Kirill Avatar asked Nov 05 '16 10:11

Kirill


2 Answers

The android plugin adds several tasks dynamically. Your .dependsOn line doesn't work because at the time gradle is trying to process this line, processDebugResources task yet available. You should tell gradle to add the dependency as soon as the upstream task is available:

tasks.whenTaskAdded { task ->
  if (task.name == 'processDebugResources') {
    task.dependsOn copyDebugAssets 
  }
}
like image 143
RaGe Avatar answered Oct 22 '22 01:10

RaGe


Why copy? Configure where the assets should be pulled from:

android {
    // other cool stuff here

    sourceSets {
        androidTest {
            assets.srcDirs = ['../testAssets']
        }
    }
}

(replacing ../testAssets with a path to where the assets should come from)

I have used this successfully with androidTest for instrumentation testing. AFAIK, it should work for test or any other source set.

like image 32
CommonsWare Avatar answered Oct 22 '22 02:10

CommonsWare