这东西辣鸡葫芦娃折腾了一天多,茶不思饭不想,终于能够跑起来了,从此省去了手动部署项目的烦恼233。在这里把踩过的一堆坑分享一下,希望能帮助到其他小伙伴。
项目配置:
mvn对项目结构有一些约束,比如约定源代码放在src/main/java 测试代码放在src/test/java,如果你的项目是按照此种方式结构,那是极好的,如果不是,源代码和测试代码路径可以再pom.xml中显式指明。
注:如果在编译过程出现无法找到org.junit.jar,可以把junit.jar添加到jdk中解决,具体位置为:jdk/jre/lib/ext,其他所有的jar包依赖问题都可以如此解决。好处在于:配置服务器资源时,可能会跑很多个java项目,他们有一些共同的依赖,比如junit、jdbc connector等,适当扩展以下jdk就不需要给每个项目单独加依赖了。缺点在于:项目部署和具体服务器有关,放到另外的没扩展过jdk的服务器上可能会无法运行。
在项目根目录下创建一个pom.xml,内容为:
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<!--以上是此mvn脚本版本信息,复制黏贴即可-->
<!--以下为项目基本信息,对构建过程无影响-->
<groupId>com.calabash_boy</groupId>
<artifactId>myapp</artifactId>
<version>1.0.0</version>
<!--以上为项目基本信息,对构建过程无影响-->
<!--以下为编译源代码+编译测试代码+执行测试代码-->
<build>
<!--指定编译的jdk版本为jdk8-->
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.0.2</version>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
<!--添加junit依赖-->
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
</plugin>
</plugins>
<!--源代码路径-->
<sourceDirectory>src/main</sourceDirectory>
<!--源代码编译输出路径-->
<outputDirectory>web/classes/main</outputDirectory>
<!--测试代码输出路径-->
<testOutputDirectory>web/classes/test</testOutputDirectory>
<!--测试代码路径-->
<testSourceDirectory>src/test</testSourceDirectory>
<!--编译源代码的资源文件,比如第三方jar包-->
<resources>
<resource>
<targetPath>web/lib</targetPath>
<directory>web/lib</directory>
</resource>
</resources>
<!--编译测试代码的资源文件,比如第三方jar包-->
<testResources>
<testResource>
<targetPath>web/lib</targetPath>
<directory>web/lib</directory>
</testResource>
</testResources>
</build>
<!--以上为编译源代码+编译测试代码+执行测试代码-->
<!--以下配置cobertura生成测试报告+测试覆盖率报告-->
<profiles>
<profile>
<id>jenkins</id>
<activation>
<property>
<name>env.BUILD_NUMBER</name>
</property>
</activation>
<!--上面一小段复制黏贴即可-->
<build>
<plugins>
<plugin>
<!-- 以下为cobertura插件信息,复制黏贴即可-->
<groupId>org.codehaus.mojo</groupId>
<artifactId>cobertura-maven-plugin</artifactId>
<version>2.7</version>
<!-- 以上为cobertura插件信息-->
<!-- 以下为jenkins导出xml报告用,复制黏贴即可-->
<configuration>
<formats>
<format>xml</format>
</formats>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>cobertura</goal>
</goals>
</execution>
</executions>
<!-- 以上为jenkins导出xml报告用>-->
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>
jenkins配置:
1、安装cobertura插件,直接到系统管理-插件管理-可选插件中选择cobertura下载安装。
2、通过shell调用mvn命令生成cobertura测试报告,先cd到pom.xml所在目录,然后执行mvn clean cobertura:cobertura package。我个人不推荐新手使用ANT脚本方式,因为ANT脚本配置cobertura有点繁琐,而mvn好处在于你不用去了解cobertura先编译,然后修改字节码生成ser,然后跑测试这么多细节,且mvn的pom.xml比ANT的build.xml好写很多。
3、构建后操作选择Publish Cobertura Coverage Report,路径选择coverage.xml所在目录,一般为项目根目录/target/site/cobertura/coverage.xml
4、最终效果