Gradle - 测试



测试任务会自动检测并执行测试源集中所有单元测试。测试执行完成后,还会生成报告。JUnit 和 TestNG 是支持的 API。

测试任务提供了一个 Test.getDebug() 方法,可以将其设置为启动以使 JVM 等待调试器。在继续执行之前,它会将调试器端口设置为 5005

测试检测

Test Task 通过检查已编译的测试类来检测哪些类是测试类。默认情况下,它会扫描所有 .class 文件。您可以设置自定义包含/排除,并且只会扫描这些类。

根据使用的测试框架(JUnit/TestNG),测试类检测使用不同的标准。使用 JUnit 时,我们扫描 JUnit 3 和 4 测试类。

如果满足以下任何条件,则该类被视为 JUnit 测试类:

  • 类或超类扩展 TestCase 或 GroovyTestCase
  • 类或超类使用 @RunWith 注解
  • 类或超类包含使用 @Test 注解的方法
  • 使用 TestNG 时,我们扫描使用 @Test 注解的方法

注意 - 抽象类不会被执行。Gradle 还会扫描测试类路径上 jar 文件中的继承树。

如果您不想使用测试类检测,可以通过将 scanForTestClasses 设置为 false 来禁用它。

测试分组

JUnit 和 TestNG 允许对测试方法进行复杂的分组。对于分组,JUnit 测试类和方法 JUnit 4.8 引入了类别的概念。测试任务允许指定您要包含和排除的 JUnit 类别。

您可以在 build.gradle 文件中使用以下代码片段对测试方法进行分组:

test {
   useJUnit {
      includeCategories 'org.gradle.junit.CategoryA'
      excludeCategories 'org.gradle.junit.CategoryB'
   }
}

包含和排除测试

Test 类具有 includeexclude 方法。这些方法可用于指定实际应运行哪些测试。

使用下面提到的代码仅运行包含的测试:

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 = "128m"
   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
广告

© . All rights reserved.