如何使用gradle在android项目中生成jacoco报告

时间:2013-11-05 15:04:39

标签: java android gradle jacoco

在java项目中,它非常简单,gradle的示例文件夹中有两个实例。 但是当我在android项目中尝试这样做时,会遇到很多问题。

我无法添加

{apply plugin: 'java'}

test {
    jacoco{
        excludes = ['org/bla/**']
        includes = ['com/bla/**']
        append = false
    }
}
与android插件有一些冲突,测试属于java插件,所以我不知道怎么做。我可以做build,checkstyle,pmd,findbugs和test,但是jacoco报告。

我的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"
        }
    }

}

目前的问题是“找不到方法jacocoTestReport()... balabala”

任何建议都会受到很大关注!

4 个答案:

答案 0 :(得分:1)

jacoco插件与Android不兼容。要获得jacoco报告,您需要自己设置课程。为此,请将此添加到您的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'
    }
}

运行测试后,您将在“build / coverage-results”目录中找到一个jacoco.exec文件

答案 1 :(得分:0)

唯一的出路是,我发现在Gradle内部有一个Ant任务,以生成Jacoco报告。您需要创建一个Ant任务,然后在build.gradle中添加:

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

ant文件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>

答案 2 :(得分:0)

您可以创建一个单独的项目来运行jacoco任务,例如合并和报告。

示例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")
}

请务必将其包含在settings.gradle

答案 3 :(得分:-2)

目前,java插件与你必须为buildscript导入的android插件不兼容。

您仍然可以在构建文件

中使用ant.java来使用Jacoco
ant {
    java { ....}}