目前为止,Spock测试都是手工进行的。完备的企业应用需要自动化拉取代码、编译、测试、生成报告,这就需要构建服务支撑,可以参考Jenkins并查询相关知识。假设你已知晓相关知识。
区分单元、集成和功能测试
功能测试需要真实环境副本进行测试。
单元测试速度快,集成和功能测试慢很多。
单元测试运行频繁,每次代码更改都需要运行;功能测试运行频率较低,一天甚至几天运行一次。
👆本例中,使用Maven启动Tomcat服务器来进行功能测试。使用mvn test运行单元测试,使用mvn verify运行功能测试(Tomcat服务启动之后)。使用Maven Failsafe插件和Tomcat插件实现:
[...rest of pom.xml....]<build><plugins>[...rest of build plugins....]<plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-failsafe-plugin</artifactId><version>2.18</version><executions><execution><goals><goal>integration-test</goal>//集成测试<goal>verify</goal>//功能测试</goals></execution></executions><configuration><useFile>false</useFile><includes><include>**/*Spec.java</include>//被测试类</includes></configuration></plugin><plugin><groupId>org.apache.tomcat.maven</groupId><artifactId>tomcat7-maven-plugin</artifactId><version>2.2</version><executions><execution><id>tomcat-run</id><goals><goal>run-war-only</goal></goals><phase>pre-integration-test</phase><configuration><fork>true</fork></configuration></execution><execution><id>tomcat-shutdown</id><goals><goal>shutdown</goal></goals><phase>post-integration-test</phase>//关闭tomcat</execution></executions></plugin></plugins></build>
测试覆盖率
Spock测试覆盖率获取途径和之前使用JUnit是一样的——使用jacoco:
[...rest of build plugins here...]<plugin><groupId>org.jacoco</groupId><artifactId>jacoco-maven-plugin</artifactId><version>0.7.4.201502262128</version><executions><execution><id>prepare-agent</id><goals><goal>prepare-agent</goal></goals></execution></executions></plugin>[...rest of pom.xml here...]
代码质量检查可以使用SonarQube:
