我必须在我的android测试上设置代码覆盖率报告,然后将其发布在声纳中。我读过没有工具和插件可以做到这一点。我正在使用gradle脚本,并且尝试使用jacoco插件cobertura,但没有结果。有什么办法解决吗?我也尝试这样做Gradle jacoco code coverage - Then publish/show in Jenkins

最佳答案

带有代码覆盖率和声纳的build.gradle示例

apply plugin: 'com.android.application'

    android {

        compileSdkVersion 20
        buildToolsVersion '20.0.0'
        defaultConfig {
            applicationId 'com.example.coverage'
            minSdkVersion 11
            targetSdkVersion 19
            versionCode 1
            versionName '1.0'
            testHandleProfiling true
            testFunctionalTest true

        }
        buildTypes {
            debug {
                testCoverageEnabled true
            }
            release {
                runProguard false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            }
        }
        compileOptions {

            apply plugin: 'sonar-runner'
        }

        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'
        }
    }

    sonarRunner {

        sonarProperties {

            property "sonar.projectKey", "coverage-example"
            property "sonar.projectName", "Coverage Example"
            property "sonar.projectVersion", "1.0"

            property "sonar.sources", "src/main/java"
            property "sonar.binaries", "build"
            property "sonar.test", "src/androidTest/java"

            property "sonar.profile", "Sonar way"
            property "sonar.language", "java"
            property "sonar.sourceEncoding", "UTF-8"

            property "sonar.dynamicAnalysis", "reuseReports"

            property "sonar.junit.reportsPath", "build/outputs/reports/coverage/debug"
            property "sonar.cobertura.reportPath", "build/outputs/reports/coverage/debug/cobertura.xml"
            property "sonar.java.coveragePlugin", "cobertura"

            property "sonar.host.url", "http://localhost:9099"
        }
    }

现在运行



现在,您将可以在此目录中看到一个包含代码覆盖率报告的xml。



现在,在运行声纳任务之前,我们必须将report.xml转换为声纳可以读取的内容,它将使用在python脚本中完成的操作,该脚本将该文件转换为插件声纳cobertura可以使用的格式。

Link the script on github
python cover2cover.py app/build/outputs/reports/coverage/debug/report.xml src/main/java > app/build/outputs/reports/coverage/debug/cobertura.xml && cp app/build/outputs/androidTest-results/connected/* app/build/outputs/reports/coverage/debug/

现在运行
gradlew sonarRunner

08-18 16:33