Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Want to run a custom gradle task only when running Unit test

How to set up gradle to run a particular custom copy task, only when running unit tests?

EDIT

I want to run these tasks when i press build, i. e only in the flavor of the build with unit test execution included.

like image 952
Bhargav Avatar asked Dec 02 '15 14:12

Bhargav


2 Answers

I've finally found the solution, with the help of this documentation which presents all the tasks that run during build, test, release etc. in a very concise manner. So by making tasks clean, preBuild depend on my copyTask I can ensure that the copy task is run every time the project is cleaned or built.

But since I don't want to run this during building or cleaning process but want to run it when I only run tests, I identified a task that compiles release unit test sources called the compileReleaseUnitTestSources but just mentioning it in build.gradle as

compileReleaseUnitTestSources.dependsOn(myCopyTask)

doesn't actually work, because gradle will give an error saying it cannot find the task compileReleaseUnitTestSources as for some reason that task is not available yet. Instead by enclosing it in a afterEvaluate block we can ensure that this block is executed after all tasks are evaluated, that way we have access to that task now, So finally I added this to my build.gradle

afterEvaluate {
    compileReleaseUnitTestSources.dependsOn(copyResDirectoryToClasses)
}

All the answers here mention to use the dependsOn keyword to attach my task to another task that is run during general build/test execution, but none of them mentioned how to go around the problem where gradle is not able to find the tasks even though you know for sure that these tasks were available and run during build/test execution.

like image 105
Bhargav Avatar answered Oct 16 '22 09:10

Bhargav


you have to set up a "customCopyTask" and make the "test-task" which does the unittests depend on the "customCopyTask" like this

task customCopyTask(type: Copy) {
    from sourceSets.test.resources
    into sourceSets.test.output.classesDir
}
test.dependsOn customCopyTask
like image 36
k3b Avatar answered Oct 16 '22 09:10

k3b