android 程式碼涵蓋範圍

來源:互聯網
上載者:User

標籤:背景   pos   多個   file   files   imp   ssd   cal   type   

背景

項目使用的是small外掛程式。一個app分為main和多個外掛程式,為了統計外掛程式的程式碼涵蓋範圍。

1 修改外掛程式

修改外掛程式build.gradle

    buildTypes {        release {...        }        debug{          minifyEnabled false          testCoverageEnabled = true   //開啟debug版本的程式碼涵蓋範圍開關          proguardFiles getDefaultProguardFile(‘proguard-android.txt‘), ‘proguard-rules.pro‘        }    }

  

因為工程原因外掛程式產生的classes檔案在下次產生的時候會變動。因此要講classes檔案拷貝到其他位置暫存。

  tasks.whenTaskAdded { task ->      if (task.name == ‘assembleRelease‘ || task.name == ‘assembleDebug‘) {          task.doLast {              println "copy classes to jacoco"              def applicationId = android.defaultConfig.applicationId              def artifactName  = applicationId.substring(applicationId.lastIndexOf(".") + 1, applicationId.length())              project.copy {                  from "build/intermediates/classes/debug"                  into "${rootDir}/../jacoco/${artifactName}/classes/debug"              }          }      }  }
2 修改main

main作為外掛程式的容器,我們的測試代碼也在這裡。所有的測試案例繼承於BaseTest.

給BaseTest的finishZ增加覆蓋率儲存功能。

        @Override        protected void finished(Description description) {            super.finished(description);            .....            generateEcFile(true);        }    /**     * 產生ec檔案     *     * @param isNew 是否重新建立ec檔案     */    public static void generateEcFile(boolean isNew) {        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd_HHmmss");        final String DEFAULT_COVERAGE_FILE_PATH = "/sdcard/coverage/" + String.format("coverage_%s.ec", df.format(new Date()));        LogUtils.i("產生覆蓋率檔案: " + DEFAULT_COVERAGE_FILE_PATH);        OutputStream out = null;        File mCoverageFilePath = new File(DEFAULT_COVERAGE_FILE_PATH);        try {            if (isNew && mCoverageFilePath.exists()) {                LogUtils.i("JacocoUtils_generateEcFile: 清除舊的ec檔案");                mCoverageFilePath.delete();            }            if (!mCoverageFilePath.exists()) {                File d = new File("/sdcard/coverage/");                d.mkdirs();                mCoverageFilePath.createNewFile();            }            out = new FileOutputStream(mCoverageFilePath.getPath(), true);            Object agent = Class.forName("org.jacoco.agent.rt.RT")                    .getMethod("getAgent")                    .invoke(null);            out.write((byte[]) agent.getClass().getMethod("getExecutionData", boolean.class)                    .invoke(agent, false));        } catch (Exception e) {            LogUtils.i("generateEcFile: " + e.getMessage());        } finally {            if (out == null)                return;            try {                out.close();            } catch (IOException e) {                e.printStackTrace();            }        }    }

編譯main,產生測試apk和debug版本的apk.

3.測試

使用測試系統進行測試

4.收集所有測試被測收集的測試資料。
    import subprocess    import os,sys    o = subprocess.check_output([‘adb‘,‘devices‘])    ls = o.split(‘\n‘)    for line in ls:        if line.endswith(‘device‘):            id_ = line.split(‘\t‘)[0]            os.makedirs(‘./report/‘+id_)            c1 = [‘adb‘,‘-s‘,id_,‘pull‘,‘/sdcard/coverage‘,‘./report/‘+id_]            print ‘ ‘.join( c1 )            o1 = subprocess.check_output(c1)            print o1
5.建立新的gradle工程,產生報告。

建立檔案夾jacocReport。

進入檔案夾運行gradle init。

修改build.gradle

apply plugin: ‘jacoco‘buildscript {    repositories {        mavenLocal()        mavenCenter()        maven { url ‘plugins‘ }    }    dependencies {        classpath ‘net.researchgate:gradle-release:2.4.1‘        classpath ‘com.android.tools.build:gradle:2.2.3‘    }}allprojects {    repositories {        mavenLocal()        mavenCenter()        flatDir {            dirs ‘libs‘        }    }}//首先先刪除舊的merge結果檔案task removeOldMergeEc(type: Delete) {    delete "${rootDir}/../jacoco/coverageMerged/mergedcoverage.ec"}task mergeReport(type:JacocoMerge,dependsOn:removeOldMergeEc){    group = "Reporting"    description = "merge jacoco report."    destinationFile= file("${rootDir}/../jacoco/coverageMerged/mergedcoverage.ec")    //這裡的ec_dir是儲存ec檔案的檔案夾    FileTree tree = fileTree("$projectDir/../jacoco/report") {        include ‘**/*.ec‘    }    def cnt =0    tree.each{      cnt++    }    println "ec file conut:"+cnt    // tree.each{f->println f}    executionData = tree  //executionData(files)}["plugin1",‘plugin2‘].each { it1->    task "Report$it1"(type: JacocoReport,dependsOn: [mergeReport]) {it ->      println "I‘m task $it"      group = "Reporting"      description = "Generate Jacoco coverage reports after running tests."      def pluginName1 =  "$it1"      println pluginName1      reports {          xml.enabled = true          html.enabled = true      }      classDirectories = fileTree(              dir: "${rootDir}/../jacoco/${pluginName1}/classes/debug",              excludes: [‘**/R*.class‘,                         ‘**/*$InjectAdapter.class‘,                         ‘**/*$ModuleAdapter.class‘,                         ‘**/*$ViewInjector*.class‘              ])      def coverageSourceDirs =[          //不需要代碼路徑      ]      sourceDirectories = files(coverageSourceDirs)      File f = new File("${rootDir}/../jacoco/coverageMerged/mergedcoverage.ec")      println ""+f.exists()      println "" + f.length()+ " bytes"      executionData = files("${rootDir}/../jacoco/coverageMerged/mergedcoverage.ec")      doFirst {          //修改claess 檔案          println "${rootDir}/../jacoco/${pluginName1}/classes/debug"          new File("${rootDir}/../jacoco/${pluginName1}/classes/debug").eachFileRecurse { file ->              if (file.name.contains(‘$$‘)) {                  println "modify " + file.name                  file.renameTo(file.path.replace(‘$$‘, ‘$‘))              }          }      }    }}task allReport(dependsOn: [Reportplugin1,Reportplugin2]){  doLast{    println "done!"  }}

 

最後上目錄

.├── main          #主apk代碼的目錄├── jacoco             #資料目錄-存放ec檔案,classes檔案├── jacocoReport       #產生報告的工程目錄 build.gradle在此├── plugin1        #外掛程式1├── plugin2        #外掛程式2

 

  

android 程式碼涵蓋範圍

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.