Skip to content

Instantly share code, notes, and snippets.

@exallium
Created September 18, 2015 14:27
Show Gist options
  • Save exallium/7fcbf6e5fe5533d57bc0 to your computer and use it in GitHub Desktop.
Save exallium/7fcbf6e5fe5533d57bc0 to your computer and use it in GitHub Desktop.
Workaround Missing Resources for Robolectric 3.0
// Workaround for missing test resources when run unit tests within android
// studio.
// This copy the test resources next to the test classes for each variant.
// Tracked at https://github.com/nenick/AndroidStudioAndRobolectric/issues/7
// Original solution comes from
// https://code.google.com/p/android/issues/detail?id=136013#c10
// apply with:
// apply from: build.workaround-missing-resources.gradle
gradle.projectsEvaluated {
// Base path which is recognized by android studio.
def testClassesPath = "${buildDir}/intermediates/classes/test/"
// Copy must be done for each variant.
def variants = android.applicationVariants.collect()
variants.each { variant ->
def variationName = variant.name.capitalize()
// Get the flavor and also merge flavor groups.
def productFlavorNames = variant.productFlavors.collect {
it.name.capitalize() }
if (productFlavorNames.isEmpty()) {
productFlavorNames = [""]
}
productFlavorNames = productFlavorNames.join('')
// Base path addition for this specific variant.
def variationPath = variant.buildType.name;
if (productFlavorNames != null && !productFlavorNames.isEmpty()) {
variationPath = uncapitalize(productFlavorNames) +
"/${variationPath}"
}
// Specific copy task for each variant
def copyTestResourcesTask =
project.tasks.create("copyTest${variationName}Resources", Copy)
copyTestResourcesTask.from("${projectDir}/src/test/resources")
copyTestResourcesTask.into("${testClassesPath}/${variationPath}")
copyTestResourcesTask.execute()
}
}
def uncapitalize(String str) {
int strLen;
if (str == null || (strLen = str.length()) == 0) {
return str;
}
return new StringBuffer(strLen)
.append(Character.toLowerCase(str.charAt(0)))
.append(str.substring(1))
.toString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment