在Gradle中编写一个任务来运行Junit测试可以使用以下方法:
build.gradle文件中添加Junit依赖:dependencies {
    testImplementation 'junit:junit:4.12'
}
task runTests(type: Test) {
    testClassesDir = sourceSets.test.output.classesDir
    classpath = sourceSets.test.runtimeClasspath
}
此任务的类型为Test,它会使用测试类的输出目录和运行时类路径来运行测试。
$ gradle runTests
这将会运行您项目中的所有Junit测试。
完整的build.gradle文件示例如下所示:
apply plugin: 'java'
dependencies {
    testImplementation 'junit:junit:4.12'
}
task runTests(type: Test) {
    testClassesDir = sourceSets.test.output.classesDir
    classpath = sourceSets.test.runtimeClasspath
}
您可以通过运行gradle runTests命令来执行Junit测试任务。