Skip to content

Instantly share code, notes, and snippets.

@loeschg
Last active August 29, 2015 14:07
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save loeschg/3ce24c34dec364270ab8 to your computer and use it in GitHub Desktop.
Save loeschg/3ce24c34dec364270ab8 to your computer and use it in GitHub Desktop.
Robolectric tests are not working with double-espresso due to it not excluding espresso files. This snippet allows you to exclude Espresso resources when running Robolectric tests. More info can be found here: http://stackoverflow.com/a/24706452/413254
/** Hook into existing tasks. */
tasks.whenTaskAdded { theTask ->
excludeEspressoFilesIfNecessary(theTask)
}
/**
* This excludes Espresso tests from Robolectric. http://stackoverflow.com/a/24706452/413254
*
* This was needed when using double-espresso. I couldn't get Robolectric to exclude them
* normally unless doing this. Double-espresso is used to fix a conflicting Dagger 1.2 dependency
* with Espresso.
*
* Android Testing. (╯°□°)╯︵ ┻━┻
*/
def excludeEspressoFilesIfNecessary(theTask) {
// Modify these if needed.
def final TEST_SRC_DIR = 'src/test/java'
def final TO_EXCLUDE = '**/espresso/**/*.java'
def final compileTestPattern= /compileTest([^ ]*)Java/
if (theTask.name.matches(compileTestPattern)) { // find all task names.
// Grabs the name of the variant to use when naming the new task.
def matcher = (theTask.name =~ compileTestPattern)
def cleanupTaskName = "touchUp${matcher[0][1]}RobolectricSourceSet"
// Exclude espresso and add the task as a dependency.
project.task(cleanupTaskName) << {
def FileTree tree = fileTree(dir: TEST_SRC_DIR)
tree.exclude TO_EXCLUDE
theTask.source = tree
}
theTask.dependsOn(cleanupTaskName)
}
}
@loeschg
Copy link
Author

loeschg commented Oct 7, 2014

From http://stackoverflow.com/a/24706452/413254 and modified to handle variants (flavors).

@asherf
Copy link

asherf commented Oct 18, 2014

line 30: should be
def FileTree tree = fileTree(dir: TEST_SRC_DIR)
otherwise gradle 2.1 gets confused

@loeschg
Copy link
Author

loeschg commented Nov 21, 2014

@asherf, I updated. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment