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.