簡體   English   中英

使用JaCoCo Gradle插件的Android測試代碼覆蓋率

[英]Android test code coverage with JaCoCo Gradle plugin

我是Gradle和Android測試的新手,但我已經將我的Android項目轉換為使用Gradle構建。

現在,我正在嘗試使用Gradle的JaCoCo插件執行Android項目的測試覆蓋。

我已將以下內容添加到build.gradle文件中:

apply plugin: 'jacoco'

當我運行“gradle jacocoTestReport”時出現以下錯誤:

Task 'jacocoTestReport' not found in root project '<project name>'.

從文檔我應該也應用插件'java'但它與插件'android'沖突。

有沒有解決的辦法?

提前致謝。

以下是我使用Jacoco

buildscript {
  repositories {
    mavenLocal()
    mavenCentral()
  }
  dependencies {
    classpath 'com.android.tools.build:gradle:0.12.+'
    classpath 'org.robolectric:robolectric-gradle-plugin:0.11.+'
  }
}

apply plugin: 'com.android.application'
apply plugin: 'robolectric'
apply plugin: 'jacoco'

android {
  compileSdkVersion 20
  buildToolsVersion "20.0.0"

  defaultConfig {
    applicationId "YOUR_PACKAGE_NAME"
    minSdkVersion 10
    targetSdkVersion 20
    testHandleProfiling true
    testFunctionalTest true
  }
  buildTypes {
    debug {
      testCoverageEnabled false
    }
    release {
      runProguard false
      proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
    }
  }
  jacoco {
    version "0.7.1.201405082137"
  }
  packagingOptions {
    exclude 'META-INF/DEPENDENCIES.txt'
    exclude 'META-INF/LICENSE.txt'
    exclude 'META-INF/NOTICE.txt'
    exclude 'META-INF/NOTICE'
    exclude 'META-INF/LICENSE'
    exclude 'META-INF/DEPENDENCIES'
    exclude 'META-INF/notice.txt'
    exclude 'META-INF/license.txt'
    exclude 'META-INF/dependencies.txt'
    exclude 'META-INF/LGPL2.1'
    exclude 'META-INF/services/javax.annotation.processing.Processor'
    exclude 'LICENSE.txt'
  }
}

robolectric {
  include '**/*Test.class'
  exclude '**/espresso/**/*.class'

  maxHeapSize "2048m"
}

jacoco {
  toolVersion "0.7.1.201405082137"
}

// Define coverage source.
// If you have rs/aidl etc... add them here.
def coverageSourceDirs = [
    'src/main/java',
]

task jacocoTestReport(type: JacocoReport, dependsOn: "connectedDebugAndroidTest") {
  group = "Reporting"
  description = "Generate Jacoco coverage reports after running tests."
  reports {
    xml.enabled = true
    html.enabled = true
  }
  classDirectories = fileTree(
      dir: './build/intermediates/classes/debug',
      excludes: ['**/R*.class',
                 '**/*$InjectAdapter.class',
                 '**/*$ModuleAdapter.class',
                 '**/*$ViewInjector*.class'
      ])
  sourceDirectories = files(coverageSourceDirs)
  executionData = files("$buildDir/jacoco/testDebug.exec")
  // Bit hacky but fixes https://code.google.com/p/android/issues/detail?id=69174.
  // We iterate through the compiled .class tree and rename $$ to $.
  doFirst {
    new File("$buildDir/intermediates/classes/").eachFileRecurse { file ->
      if (file.name.contains('$$')) {
        file.renameTo(file.path.replace('$$', '$'))
      }
    }
  }
}


dependencies {
  androidTestCompile('junit:junit:4.11') {
    exclude module: 'hamcrest-core'
  }
  androidTestCompile('org.robolectric:robolectric:2.3') {
    exclude module: 'classworlds'
    exclude module: 'maven-artifact'
    exclude module: 'maven-artifact-manager'
    exclude module: 'maven-error-diagnostics'
    exclude module: 'maven-model'
    exclude module: 'maven-plugin-registry'
    exclude module: 'maven-profile'
    exclude module: 'maven-project'
    exclude module: 'maven-settings'
    exclude module: 'nekohtml'
    exclude module: 'plexus-container-default'
    exclude module: 'plexus-interpolation'
    exclude module: 'plexus-utils'
    exclude module: 'wagon-file'
    exclude module: 'wagon-http-lightweight'
    exclude module: 'wagon-http-shared'
    exclude module: 'wagon-provider-api'
    exclude group: 'com.android.support', module: 'support-v4'
  }
}

上述代碼還包含https://code.google.com/p/android/issues/detail?id=69174的解決方法。

更多細節: http//chrisjenx.com/gradle-robolectric-jacoco-dagger/

我正在使用JaCoCo進行使用RoboGuice,Butterknife和Robolectric的項目。 我能夠使用@Hieu Rocker的解決方案來設置它,但是有一些小缺點,即在我們的項目中,我們使用flavor並對這些flavor進行一些額外的測試以及每個的額外java代碼。 我們還使用不同的構建類型。 因此,依賴“testDebug”任務的解決方案還不夠好。 這是我的解決方案:在app模塊中的build.gradle中添加

apply from: '../app/jacoco.gradle'

然后在app模塊中創建一個jacoco.gradle文件,其中包含以下內容:

apply plugin: 'jacoco'

    jacoco {
        toolVersion "0.7.1.201405082137"
    }

    def getFlavorFromVariant(String variantName) {
        def flavorString = variantName.replaceAll(/(.*)([A-Z].*)/) { all, flavorName, buildTypeName ->
           flavorName
        }
        return flavorString;
    }

    def getBuildTypeFromVariant(String variantName) {
        def buildTypeString = variantName.replaceAll(/(.*)([A-Z].*)/) { all, flavorName, buildTypeName ->
            "${buildTypeName.toLowerCase()}"
        }
        return buildTypeString;
    }

    def getFullTestTaskName(String variantName) {
        return "test${variantName.capitalize()}UnitTest";
    }

    android.applicationVariants.all { variant ->
        def variantName = variant.name;
        def flavorFromVariant = getFlavorFromVariant("${variantName}");
        def buildTypeFromVariant = getBuildTypeFromVariant("${variantName}");
        def testTaskName = getFullTestTaskName("${variantName}")

        task ("jacoco${variantName.capitalize()}TestReport", type: JacocoReport, dependsOn: testTaskName) {
            group = "Reporting"
            description = "Generate JaCoCo coverage reports after running tests for variant: ${variantName}."
            reports {
                xml.enabled = true
                html.enabled = true
            }

            classDirectories = fileTree(
                    dir: "./build/intermediates/classes/${flavorFromVariant}/${buildTypeFromVariant}",
                    excludes: ['**/R*.class',
                               '**/*$InjectAdapter.class',
                               '**/*$ModuleAdapter.class',
                               '**/*$ViewInjector*.class'
                    ]
            )

            logger.info("Configuring JaCoCo for flavor: ${flavorFromVariant}, buildType: ${buildTypeFromVariant}, task: ${testTaskName}");

            def coverageSourceDirs = [
                    '../app/src/main/java',
                    "../app/src/${flavorFromVariant}/java"
            ]
            sourceDirectories = files(coverageSourceDirs)
            executionData = files("$buildDir/jacoco/${testTaskName}.exec")
            // Bit hacky but fixes https://code.google.com/p/android/issues/detail?id=69174.
            // We iterate through the compiled .class tree and rename $$ to $.
            doFirst {
                new File("$buildDir/intermediates/classes/").eachFileRecurse { file ->
                    if (file.name.contains('$$')) {
                        file.renameTo(file.path.replace('$$', '$'))
                    }
                }
            }
        }
    }

您可以從命令行執行它,如下所示:

.gradlew jacocoFlavor1DebugTestReport

要么

.gradlew jacocoOtherflavorPrereleaseTestReport

在我們的項目中,我們使用一個約定,不要在flavor和build類型名稱中使用大寫字母,但如果你的項目不遵循這個約定,你只需更改getFlavorFromVariant(..)getBuildTypeFromVariant(..)函數

希望這有助於某人

您可以嘗試使用此Gradle插件: https//github.com/arturdm/jacoco-android-gradle-plugin

這里的答案還有一點https://stackoverflow.com/a/32572259/1711454

您是否嘗試添加以下內容:

jacocoTestReport {
   group = "Reporting"
   description = "Generate Jacoco coverage reports after running tests."
   additionalSourceDirs = files(sourceSets.main.allJava.srcDirs)
}

然后運行./gradlew jacocoTestReport而不是運行./gradlew test jacocoTestReport

如果一切順利,您應該在build/reports/jacoco/test/html/index.html找到測試結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM