使用JaCoCo Gradle插件进行Androidtesting代码覆盖

我是新来的Gradle和Androidtesting,但我已经转换我的Android项目与Gradle构build。

现在我试图用Gradle的JaCoCo插件来testing一个Android项目的testing覆盖率。

我已经将以下内容添加到了我的build.gradle文件中:

apply plugin: 'jacoco' 

而当我运行“gradle jacocoTestReport”时出现以下错误:

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

从文档我应该也应用插件'java',但它与插件'android'冲突。

有没有解决的办法?

提前致谢。

Solutions Collecting From Web of "使用JaCoCo Gradle插件进行Androidtesting代码覆盖"

下面是我如何使用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的解决方法&#x3002;

更多详情: http : //chrisjenx.com/gradle-robolectric-jacoco-dagger/

我正在使用RoCoGuice,Butterknife和Robolectric的项目来使用JaCoCo。 我可以使用@Hieu Rocker的解决scheme进行设置,但是也存在一些小缺陷,即在我们的项目中我们使用了flavor,并且为这些flavor添加了一些额外的testing以及为它们每个添加了额外的java代码。 我们也使用不同的构buildtypes。 因此,依赖“testDebug”任务的解决scheme还不够好。 这是我的解决scheme:在应用程序模块添加build.gradle

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

然后用以下内容在app模块中创build一个jacoco.gradle文件:


    套用插件:'jacoco'

     jacoco {
         toolVersion“0.7.1.201405082137”
     }

     def getFlavorFromVariant(String variantName){
         def flavorString = variantName.replaceAll(/(。*)([AZ]。*)/){all,flavorName,buildTypeName  - >
            flavorName
         }
        返回flavorString;
     }

     def getBuildTypeFromVariant(String variantName){
         def buildTypeString = variantName.replaceAll(/(。*)([AZ]。*)/){all,flavorName,buildTypeName  - >
             “$ {buildTypeName.toLowerCase()}”
         }
        返回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}”)

        任务(“jacoco $ {variantName.capitalize()} TestReport”,键入:JacocoReport,dependsOn:testTaskName){
             group =“报告”
             description =“在运行变体testing后生成JaCoCo覆盖率报告:$ {variantName}”。
            报告{
                 xml.enabled = true
                 html.enabled = true
             }

             classDirectories = fileTree(
                     dir:“./build/intermediates/classes/${flavorFromVariant}/${buildTypeFromVariant}”,
                    排除:['** / R * .class',
                                '** / * $ InjectAdapter.class',
                                '** / * $ ModuleAdapter.class',
                                '** / * $ ViewInjector的* .class'
                     ]
             )

             logger.info(“configurationJaCoCo的风味:$ {flavorFromVariant},buildType:$ {buildTypeFromVariant},任务:$ {testTaskName}”);

             def coverageSourceDirs = [
                     '../app/src/main/java',
                     “../app/src/${flavorFromVariant}/java”
             ]
             sourceDirectories = files(coverageSourceDirs)
             executionData = files(“$ buildDir / jacoco / $ {testTaskName} .exec”)
             / /有点哈克,但修复https://code.google.com/p/android/issues/detail?id=69174。
             //我们遍历已编译的.class树并将$$重命名为$。
             doFirst {
                新文件(“$ buildDir / intermediates / classes /”)。eachFileRecurse {file  - >
                     if(file.name.contains('$$')){
                         file.renameTo(file.path.replace('$$','$'))
                     }
                 }
             }
         }
     }

你可以像这样从命令行执行它:

 .gradlew jacocoFlavor1DebugTestReport 

要么

 .gradlew jacocoOtherflavorPrereleaseTestReport 

在我们的项目中,我们使用一个约定,不要在flavor中使用大写字母和构buildtypes名称,但是如果你的项目不遵循这个约定,你可以简单的改变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.htmlfindtesting结果。