Running unit tests before each build in Gradle

2019-03-25 18:59发布

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?

2条回答
再贱就再见
2楼-- · 2019-03-25 19:27

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.enter image description here

enter image description here

else for pre gradle task refer here

查看更多
放荡不羁爱自由
3楼-- · 2019-03-25 19:32

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.

查看更多
登录 后发表回答