Sonar QA
Sonar作用:七个维度检测代码质量:
(1)复杂度分布(complexity):代码复杂度过高将难以理解
(2) 重复代码(duplications):程序中包含大量复制、粘贴的代码而导致代码臃肿,sonar可以展示源码中重复严重的地方
(3) 单元测试统计(unit tests):统计并展示单元测试覆盖率,开发或测试可以清楚测试代码的覆盖情况
(4) 代码规则检查(coding rules):通过Findbugs,PMD,CheckStyle等检查代码是否符合规范
(5) 注释率(comments):若代码注释过少,特别是人员变动后,其他人接手比较难接手;若过多,又不利于阅读
(6) 潜在的Bug(potential bugs):通过Findbugs,PMD,CheckStyle等检测潜在的bug
(7) 结构与设计(architecture & design):找出循环,展示包与包、类与类之间的依赖、检查程序之间耦合度
环境:Windows10,Sonarqube7.4,Java1.8,Mysql5.7
首先从Sonar官网下载相关的Sonarqube与SonarScanner相关版本并且安装 官网地址:https://www.sonarqube.org/downloads
一、环境配置
Sonar需要一些辅助软件,需要自己提前安装
1、 JDK的安装,版本要求要1.8,不支持1.7版本
2、 数据库的安装
然后配置相关环境变量:
JAVA_HOME:C:\Program Files\Java\jdk1.8.0_171
Path:C:\Program Files\Java\jdk1.8.0_171\bin
D:\mysql-5.7.23-winx64\bin
D:\Sonar\sonar-scanner-3.2.0\bin
三、Sonar配置
1.文件路径:D:\Sonar\sonarqube-7.4\conf\sonar.properties
sonar.jdbc.url=jdbc:mysql://localhost:3306/sonar_data?useUnicode=true&characterEncoding=utf8&rewriteBatchedStatements=true&useConfigs=maxPerformance
sonar.jdbc.username=root
sonar.jdbc.password=root
sonar.sorceEncoding=UTF-8
sonar.login=admin
sonar.password=admin
2.文件路径:D:\Sonar\sonar-scanner-3.2.0\conf\sonar-scanner.properties
sonar.jdbc.url=jdbc:mysql://localhost:3306/sonar_data?useUnicode=true
&characterEncoding=utf8&rewriteBatchedStatements=true&useConfigs=maxPerformance
sonar.jdbc.username=root
sonar.jdbc.password=root
注意:如果测试项目与服务器不在同一台机子,则需要添加服务器的IP:
#----- Default SonarQube server sonar.host.url=http://XXX.XXX.XXX.XXX:9000
三、数据库创建
CREATE DATABASE sonar_data CHARACTER SET utf8 COLLATE utf8_general_ci;
四、启动服务
在Sonar安装目录下(D:\Sonar\sonarqube-7.4\bin\windows-x86-64)我是Windows64位,选择Windows-x86-64
双击StartSonar.bat文件,启动sonar
服务启动后就可以通过相关端口访问 我是:http://localhost:9000 (默认端口是9000)
# TCP port for incoming HTTP connections. Default value is 9000.
#sonar.web.port=9000
五、代码扫描
打开要进行代码分析的项目根目录,新建sonar-project.properties文件
在sonar安装目录下打开
输入如下信息
# must be unique in a given SonarQube instance
sonar.projectKey=TestDemo
# this is the name displayed in the SonarQube UI
sonar.projectName=TestDemo
sonar.projectVersion=1.0
# Path is relative to the sonar-project.properties file. Replace "\" by "/" on Windows.
# Since SonarQube 4.2, this property is optional if sonar.modules is set.
# If not set, SonarQube starts looking for source code from the directory containing
# the sonar-project.properties file.
sonar.sources=src
sonar.binaries=TestDemo/target/sonar #Sonar7.0后的版本必须加
# Encoding of the source code. Default is default system encoding
sonar.sourceEncoding=UTF-8
sources是源文件所在的目录,projectName是项目名字,projectKey可以和项目名一致(要保证唯一,直接用项目名比较合适)
设置成功后,启动sonarqube服务然后在cmd进入项目所在的根目录,输入命令:sonar-scanner
或者不想维护sonar-project.properties文件,直接使用maven命令
mvn sonar:sonar -Dsonar.java.binaries=target/classes
-D 和sonar.java.binaries 之间不能有空格,等号后面的路径就是指定的文件目录了
最后打开http://localhost:9000/,我们会看到主页出现了分析项目的概要图