sonar导入android emma单元测试报告的方法

代码质量这个事儿一直是组内关注的重点,指标包括findbugs、checkstyle和单元测试覆盖。一直以来前两个静态检查都是采用eclipse安装相应插件的方法,单元测试采用命令行emma生成。刚开始时工程数量比较少,还能撑得住,后来工程越来越多,弄一次报告统计要浪费不少时间,手动效率着实低的可以。正琢磨着换换工具,忽然在某次课程分享中听到了sonar,发现确实省事,而且统计的指标和形式也很多,初试很爽,到最后卡在了单元测试覆盖率这个指标上,专门抽了一个上午弄了一下,终于搞通,这里做个笔记。

我这边场景还是比较古朴的,android工程以往采用的是emma报告,生成报告这一步可以统一弄个shell脚本搞定,那么比较简单粗暴的方法就是想个辙——把生成好的报告结果导入进sonar的数据库就万事大吉了。
所谓“外事不决问谷歌”,找到一篇国际友人的博客,Android Unit Tests and Coverage in Sonar ,虽然时间略久远但是还是非常具有指导意义,该大牛把这个事儿主要分了一下几步:

  1. 使用eclipse生成单元测试报告;
  2. 把测试报告的各路结果弄到一个工程目录下面去;
  3. 弄一个能被sonar读明白的配置文件;
  4. 配置sonar插件,让它能读上面那个配置文件;
  5. 把文件路径跟sonar-runner的配置再关联在一起;
  6. 走起sonar-runner,出结果;

大概齐是这样一个过程,但是有些步骤现在的环境不合适,比如生成报告,现在的方法跟博客中介绍的已有不同;再比如导入emma的插件,博文中介绍的Sonar-emma-plugin-1.2.1 with EMMA 2.0 目前已不推荐使用。不过总体流程大体不差,磕磕绊绊终于弄通了,具体分下面几步:

1.修改android sdk 中 ant配置,防止中间文件被删除;
如上面博文所说:
找到 your-android-sdk-dir/tools/ant/build.xml ,打开;
搜索关键词“Cleaning up temporary files”;
干掉关键词附近的下面这两行:

<delete file="${out.absolute.dir}/coverage.ec" />
<delete file="${out.absolute.dir}/coverage.em" />

经常折腾emma单元测试的人对coverage.xx 这两个文件应当不会陌生。

2.安装sonar插件,Android Plugin;
Sonar-emma-plugin-1.2.1 with EMMA 2.0这东西已经不推荐使用了,在这货的链接网页里发现了推荐Android Plugin,在Android Plugin的主页中有这么两段介绍:

Makes the plugin compatible with multi-language analysis introduced in SonarQube 4.2 and adds support of Emma 2.0 reports

Code Coverage
To display code coverage data:
Prior to the SonarQube analysis, execute your unit tests and generate the Emma 2.0 reports (.em and .ec files)
Import these reports while running the SonarQube analysis by setting the sonar.android.emma.report property to the path of the directory containing the Emma reports. The path may be absolute or relative to the project base directory for standard projects, relative to the module base directory for multi-module projects.

确定事情能办,并且提供了配置方法。装好插件,继续干活。

3.生成报告,集合文件;
生成报告就不多说了,就是当下emma生成报告的方法。值得一提的是:coverage.em 这个文件默认在主工程bin文件夹下;coverage.ec 与相关的其他文件在测试工程的bin文件夹下,我目前的处理是把coverage.em拷贝到测试工程的bin下面去,由于不了解具体文件功能,所以这里是否合适还不明确。留一段脚本代码:

clean_project()
{
  cd $1
  rm -rf bin gen
  android update project -p .
}

emma_run()
{
  mainpath=$1
  testpath=$2
  clean_project $mainpath
  android update test-project -m $mainpath -p $testpath
  clean_project $testpath
  ant emma debug install test
  cp $mainpath"/bin/coverage.em" $testpath/bin
}

4.配置sonar-runner 的配置文件;
按照Android Plugin的代码覆盖率导入那一段介绍来,在主工程目录下的sonar-runner的配置文件sonar-project.properties 中添加一句:

sonar.android.emma.report=../MainProjectTest/bin/

5.到主工程目录下,sonar-runner 走起。

这样基本就能在sonar结果中看到测试覆盖率的导入了。不过有一些小问题,就是只能看到覆盖率,用例数、行覆盖、方法覆盖、块覆盖都不见了。
估计是在第三步的拷贝操作漏掉了什么东西,先记于此,日后找到原因更新。

感谢您赏个荷包蛋~