简体   繁体   English

如何使用Gradle在Android项目中生成Jacoco报告

[英]How to generate jacoco report in android project with gradle

In java project it's very easy,there are two instances in gradle's sample folder. 在Java项目中,这非常容易,gradle的示例文件夹中有两个实例。 But when I try to do it in android project,there're a lot of problems. 但是当我尝试在android项目中执行此操作时,存在很多问题。

I can't add 我无法添加

{apply plugin: 'java'}

and

test {
    jacoco{
        excludes = ['org/bla/**']
        includes = ['com/bla/**']
        append = false
    }
}

There are some conflicts with android plugin,test is belong to java plugin,so I don't konw how to do. 与android插件存在一些冲突,测试属于Java插件,所以我不知道该怎么做。 I can do build,checkstyle,pmd,findbugs and test,but jacoco report. 我可以进行构建,检查样式​​,pmd,findbug和测试,但是可以进行报告。

My gradle file is below: 我的gradle文件如下:

//Import android test dependencies
import com.android.build.gradle.api.TestVariant


//Load classpath and define the repository.
buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.6.+'
    }
}


//Sub project,we can add a lot of sub project here.
project('TVEAndroid')
{

    //Load plugins
    apply plugin: 'android'
    apply plugin: 'jacoco'
    apply plugin: 'checkstyle'
    apply plugin: 'findbugs'
    apply plugin: 'pmd'


    //This is different with the one above,the previous one is just for load classpath,this one is for the real build.
    repositories {
        mavenCentral()
        }

    //Load dependencies,We will use nesux to hold the repositories in the future,so it will be changed.
    dependencies {
        compile fileTree(dir: 'libs', include: '*.jar')
    }

    //Jacoco plugin information declaration,but jacoco didn't work here,but it works in the java project with the same configuration. 
    jacoco {
        toolVersion = "0.6.2.201302030002"
        reportsDir = file("$buildDir/customJacocoReportDir")
    }


    //Define android build information
    android {
        compileSdkVersion 18
        buildToolsVersion "18.1.1"

        sourceSets {
            main {
                manifest.srcFile 'AndroidManifest.xml'
                java.srcDirs = ['src']
                resources.srcDirs = ['src']
                aidl.srcDirs = ['src']
                renderscript.srcDirs = ['src']
                res.srcDirs = ['res']
                assets.srcDirs = ['assets']
            }

             //Set the build path,the root folder
            instrumentTest.setRoot('../TVEAndroidTest')

            //Set the code and resuource path for build
            instrumentTest {
                java { srcDirs = [
                       '../TVEAndroidTest/src/'
                   ] }
              res.srcDirs = ['res']
               assets.srcDirs = [
                    '../TVEAndroidTest/assets'
               ]
                resources.srcDirs = [
                    '../TVEAndroidTest/src'
                ]

            }


            //Define the package name for build
            defaultConfig {
                testPackageName "com.accedo.android.tve.test"
                testInstrumentationRunner "android.test.InstrumentationTestRunner"
            }

            // Move the build types to build-types/<type>
            // For instance, build-types/debug/java, build-types/debug/AndroidManifest.xml, ...
            // This moves them out of them default location under src/<type>/... which would
            // conflict with src/ being used by the main source set.
            // Adding new build types or product flavors should be accompanied
            // by a similar customization.
            debug.setRoot('build-types/debug')
            release.setRoot('build-types/release')
        }
    }

    jacoco {
        append = false
        destinationFile = file("$buildDir/jacoco/jacocoTest.exec")
        classDumpFile = file("$buildDir/jacoco/classpathdumps")
    }

    //PMD task
    task pmd(type: Pmd) {
        ruleSetFiles = files('../config/quality/pmd/pmd-ruleset.xml')
        ruleSets = ["basic", "braces", "strings"]
        source = android.sourceSets.main.java.srcDirs
    }

    //CheckStyle task
    task checkstyle(type: Checkstyle) {
        configFile file('../config/quality/checkstyle/checkstyle.xml')  
        source android.sourceSets.main.java.srcDirs
        include '**/*.java'
        exclude '**/gen/**'

        classpath = files( project.configurations.compile.asPath )
    }

    //Findbugs task
    task findbugs(type: FindBugs) {

        excludeFilter file('../config/quality/findbugs/findbugs-filter.xml')
        classes = fileTree('build/classes/debug')
        source = android.sourceSets.main.java.srcDirs
        classpath = files( project.configurations.compile.asPath )

        reports {
            xml {
                destination "build/reports/findbugs/findbugs.xml"
            }
        }

        effort = 'max'
    }

    jacocoTestReport {
        reports {
        xml.enabled false
        csv.enabled false
        html.destination "${buildDir}/jacocoHtml"
        }
    }

}

The current problem is "Could not find method jacocoTestReport() ...balabala" 当前的问题是“找不到方法jacocoTestReport()... balabala”

Any advice will be greatly appriciated! 任何建议将不胜感激!

The jacoco plugin is not compatible with Android. jacoco插件与Android不兼容。 To get jacoco reports you need to instrument your classes on your own. 要获取jacoco报告,您需要自己对课程进行检测。 To achieve that add this to your gradle build config file : 为此,请将其添加到gradle构建配置文件中:

configurations {
   codeCoverage
   codeCoverageAnt
}
dependencies {
   codeCoverage 'org.jacoco:org.jacoco.agent:0.5.10.201208310627:runtime@jar'
   codeCoverageAnt 'org.jacoco:org.jacoco.ant:0.5.10.201208310627'
}

tasks.whenTaskAdded { task ->
    if (task.name == 'testDefaultFlavorDebug') { /* Name of your test task */
       task.jvmArgs "-javaagent:${configurations.codeCoverage.asPath}=destfile=${project.buildDir.path}/coverage-results/jacoco.exec,sessionid=HSServ,append=false",
            '-Djacoco=true',
            '-Xms128m',
            '-Xmx512m',
            '-XX:MaxPermSize=128m'
    }
}

After running your tests you will have a jacoco.exec file in 'build/coverage-results' directory 运行测试后,您将在“ build / coverage-results”目录中拥有一个jacoco.exec文件。

The only way out for this, I found is to have an Ant task inside of Gradle, to generate Jacoco report. 我发现唯一的解决方法是在Gradle中有一个Ant任务,以生成Jacoco报告。 You will need to create an Ant task and then in build.gradle, add this: 您将需要创建一个Ant任务,然后在build.gradle中添加以下内容:

task coverage(dependsOn: test_task) <<{ /* Name of your test task */
        ant.importBuild 'ant-coverage.xml'
    }

The ant file ant-coverage.xml is as follows: 蚂蚁文件ant-coverage.xml如下:

<?xml version="1.0" encoding="UTF-8"?>
<project name="project_name" xmlns:jacoco="antlib:org.jacoco.ant">
<property name="jacoco.dir" value="${basedir}/../../jacoco"/>
<property name="src.dir" value="./src"/>
<property name="build.dir" value="./build"/>
<property name="jacoco.exec.file" value="${build.dir}/coverage-results/jacoco.exec"/>
<property name="classes.dir" value="${build.dir}/classes/release/"/>
<property name="result.report.dir" value="${build.dir}/reports"/>

<taskdef uri="antlib:org.jacoco.ant" resource="org/jacoco/ant/antlib.xml">
    <classpath path="${jacoco.dir}/lib/jacocoant.jar"/>
</taskdef>

<jacoco:report>
    <executiondata>
        <file file="${jacoco.exec.file}"/>
    </executiondata>
    <structure name="Coverage">
        <classfiles>
            <fileset dir="${classes.dir}/"/>
        </classfiles>
        <sourcefiles>
            <fileset dir="${src.dir}"/>
        </sourcefiles>
    </structure>
    <html destdir="${result.report.dir}"/>
</jacoco:report>

</project>

You can create a separate project to run jacoco tasks such as merge and report. 您可以创建一个单独的项目来运行jacoco任务,例如合并和报告。

Example build.gradle : 示例build.gradle

apply plugin: 'java'
apply plugin: 'jacoco'

jacocoTestReport {
  reports {
      xml.enabled true
  }

  group = "Reporting"
  description = "Generate Jacoco coverage reports after running tests."

  additionalSourceDirs = files("$project.rootDir/yourProject/src/main/java")
  additionalClassDirs = files("$project.rootDir/yourProject/build/classes/googleplay/debug/")

  executionData = files("$project.rootDir/yourProject/build/jacoco/yourFlavor/debug/jacoco.exec")
}

Make sure to include it in your settings.gradle . 确保将其包括在settings.gradle

At this moment, the java plugin is not compatible with the android plugin that you have to import for the buildscript. 目前,java插件与您必须为构建脚本导入的android插件不兼容。

You can still use Jacoco by using ant.java inside the build file 您仍然可以通过在构建文件中使用ant.java来使用Jacoco

ant {
    java { ....}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Gradle:如何使用 jacoco 生成集成测试的覆盖率报告 - Gradle : How to generate coverage report for Integration test using jacoco 在Android项目中使用JaCoCo和Gradle - Use JaCoCo in Android Project with Gradle 使用gradle生成单个单元测试的Jacoco代码覆盖率报告 - Generate Jacoco code coverage report for individual unit tests using gradle 如何为 JAR 文件生成 JaCoCo 报告? - How do I generate a JaCoCo report for a JAR file? 带有 Jacoco 插件的 build.gradle 不会为集成测试生成覆盖率报告 - build.gradle with Jacoco plugin doesn't generate coverage report for integration tests Jacoco Maven多模块项目报告 - Jacoco report for maven multimodule project 如何将Maven项目Jacoco覆盖率报告专家告知xml,Jacoco执行 - how to intellij maven project jacoco coverage report expert to xml, jacoco exec 用gradle从黄瓜测试中获取jacoco报告 - Getting jacoco report from cucumber tests with gradle How to generate cucumber html report with attached failed screenshot and cucumber.json file using gradle based project - How to generate cucumber html report with attached failed screenshot and cucumber.json file using gradle based project maven jacoco 插件不生成覆盖率报告 - maven jacoco plugin does not generate coverage report
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM