如何为新任务类型扩展Gradle任务的行为?

zgg*_*ame 8 groovy task gradle

我想为一些测试任务设置一些东西.更具体地说,我想添加一些环境变量和一些系统属性,可能还有一些其他的东西,比如"dependencies"或"workingDir".通过常规Test任务,我可以做到这一点,

task test1(type:Test, dependsOn:[testPrep,testPrep1]){
     workingDir testWorkingPath
     systemProperty 'property','abs'
     environment.find { it.key ==~ /(?i)PATH/ }.value += (System.properties['path.separator'] + myLibPath)
     environment.LD_LIBRARY_PATH = "/usr/lib64:/lib64:${myLibPath}:" + environment.LD_LIBRARY_PATH
 }

task test2(type:Test, dependsOn:[testPrep]){
     workingDir testWorkingPath
     systemProperty 'property','abs'
     environment.find { it.key ==~ /(?i)PATH/ }.value += (System.properties['path.separator'] + myLibPath)
     environment.LD_LIBRARY_PATH = "/usr/lib64:/lib64:${myLibPath}:" + environment.LD_LIBRARY_PATH
     systemPropety 'newProperty','fdsjfkd'
 }
Run Code Online (Sandbox Code Playgroud)

如果有一个新的任务类型MyTestType扩展常规的Test任务类型,定义了通用定义,那就太好了.

task test1(type:MyTestType){
     dependsOn testPrep1
 }

task test2(type:MyTestType){
     systemPropety 'newProperty','fdsjfkd'
 } 
Run Code Online (Sandbox Code Playgroud)

最好的方法是什么?似乎该execute()方法是最终的,不能扩展.我需要做一些像doFirst设置这些属性的事情.我应该在构造函数中添加所有额外的值吗?我可以使用其他任何钩子吗?谢谢.

Ren*_*hke 11

通常,您可以扩展"测试"任务并实现自定义

task test1(type:MyTestType){
}

task test2(type:MyTestType){
     systemProperty 'newProperty','fdsjfkd'
}

class MyTestType extends Test {
    public MyTestType(){
        systemProperty 'property','abs'
    }
}
Run Code Online (Sandbox Code Playgroud)

或者,您可以Test使用较少的样板配置所有类型的任务:

// will apply to all tasks of type test. 
// regardless the task was created before this snippet or after
tasks.withType(Test) {
   systemProperty 'newProperty','fdsjfkd'   
}
Run Code Online (Sandbox Code Playgroud)