测试任务自动检测和执行测试源集合中的所有单元测试。它还会在测试执行完成后生成报告。 JUnit和TestNG都是支持的API。
测试任务提供了一个Test.set Debug()
方法,可以将其设置为启动JVM
等待调试器。在继续执行之前,它将调试器发布值设置为5005
。
测试任务通过检查编译的测试类来检测哪些类是测试类。 默认情况下,它扫描所有.class
文件。不过也可以设置自定义包含/排除,只有那些类才会被扫描。根据所使用的测试框架(JUnit
/TestNG
),测试类检测使用不同的标准。
如果不想使用测试类检测,可以通过将scanForTestClasses
设置为false
来禁用它。
JUnit
和TestNG
允许复杂的测试方法分组。对于分组,JUnit
有测试类和方法。JUnit 4.8
引入了类别的概念。测试任务允许指定要包括或排除的JUnit
类别。
可以使用build.gradle
文件中的以下代码段对测试方法进行分组。如下代码所示
test { |
useJUnit { |
includeCategories 'org.gradle.junit.CategoryA' |
excludeCategories 'org.gradle.junit.CategoryB' |
} |
} |
Test
类有一个include
和exclude
方法。这些方法可以用于指定哪些测试应该运行。
只运行包含的测试
test { |
include '**my.package.name/*' |
} |
test { |
exclude '**my.package.name/*' |
} |
build.gradle
示例文件显示了不同的配置选项。
apply plugin: 'java' // adds 'test' task |
test { |
// enable TestNG support (default is JUnit) |
useTestNG() |
// set a system property for the test JVM(s) |
systemProperty 'some.prop', 'value' |
// explicitly include or exclude tests |
include 'org/foo/**' |
exclude 'org/boo/**' |
// show standard out and standard error of the test JVM(s) on the console |
testLogging.showStandardStreams = true |
// set heap size for the test JVM(s) |
minHeapSize = "64m" |
maxHeapSize = "512m" |
// set JVM arguments for the test JVM(s) |
jvmArgs '-XX:MaxPermSize=256m' |
// listen to events in the test execution lifecycle |
beforeTest { |
descriptor → logger.lifecycle("Running test: " + descriptor) |
} |
// listen to standard out and standard error of the test JVM(s) |
onOutput { |
descriptor, event → logger.lifecycle |
("Test: " + descriptor + " produced standard out/err: " |
+ event.message ) |
} |
} |
gradle <someTestTask> --debug-jvm |