Skip to content

Instantly share code, notes, and snippets.

@lordcodes
Last active January 18, 2016 23:36
Show Gist options
  • Save lordcodes/25a9da2b8079c968aa57 to your computer and use it in GitHub Desktop.
Save lordcodes/25a9da2b8079c968aa57 to your computer and use it in GitHub Desktop.
Workaround for test resources file not being found by Robolectric. You will need to add: "apply from: 'build-test-fixes.gradle'" to your main build.gradle file.
// 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
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