How can I configure a build.gradle
in an Android project to run all my unit tests before each debug or release build? I know that I can set tasks dependencies with dependsOn
, but how can I specify it for the unit test task? I'd like to do this for each (Android and plain Java) module of my project, is it possible?

- 1,933
- 7
- 28
- 47
2 Answers
Do you have a special task to run only unit tests? Or you are free to run it as simple test
(or more generally testDebug
and testRelease
)? Let's say, you want to run testDebug
or testRelease
every time you call assembleDebug
or assembleRelease
task. Then you can, as you've noted, use dependsOn
task property. For example this way:
assembleDebug.dependsOn testDebug
assembleRelease.dependsOn testRelease
This configuration must be added to every build.gradle script (in every module of the project), where you need it. If you have a number of test tasksm you can set task dependencies this way:
tasks.assembleRelease.dependsOn {
project.tasks.findAll { task ->
task.name.startsWith('testRelease')
}
}
Sure, you can try to set this dependencies in the root the root build.gradle script, by using allprojects
or subprojects
(you can read about it here), but you have to apply android
plugin in the root script too, otherwise tasks won't be found.

- 27,441
- 9
- 87
- 82
-
4I have a project with both Android and plain Java modules. I only have simple JUnit tests for now. In my plain Java modules everything seems to work fine with `jar.dependsOn test` at the end of the gradle file (if a test fails, the build stops). In my Android modules, with `assembleDebug.dependsOn testDebug` I get the error `Could not find property 'testDebug' on BuildType_Decorated`. Where should I put this line? Thanks! – manfcas Jul 30 '16 at 08:13
Go to Run/Debug Configurations, and select your application configuration. At the bottom of the right panel, under Before launch:, click the + button, and select Run another configuration. There, choose the configuration for running your tests.
In before launch set your test case command to run them.
else for pre gradle task refer here
-
Thanks, I didn't know about this option! In this way, though, the configuration is not included in the `build.gradle` files, and so isn't shared through VCS. I'd like it to be shared with all of my team. – manfcas Jul 30 '16 at 11:09
-
You can update steps in your README.md file for that else you can export your IDE setting and share with your team (file>export settings). – Rax Jul 30 '16 at 11:13
-
-
On CI you can set upstream / down stream projects so for unit tests create a project for unit test and one project will be your main building project thus in your main project set upstream project as your unit test project or in other way set your main project as a down stream in unit test project. – Rax Jul 30 '16 at 11:18