前言: 对Eclipse的工程写单元测试:
1. 一个工程有多个测试类,将测试类放到一个测试包下。
2. 每一个测试类写好,都单独执行run as ->JUnit Test测一下。
3. Junit 测试报告简单明了。
一、使用maven-surefire-plugin插件自带report功能
注意:
1、单独运行mvn test,默认执行的就是maven-surefire-plugin
2、配置了maven-surefire-plugin后,运行mvn test,结果和1一致,生成xml、txt文件
3、运行mvn test surefire-report:report 即是:运行mvn test的基础上,根据生成的xml、txt文件,再生成默认格式的report
<plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.0.2</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> <configuration> <testFailureIgnore>true</testFailureIgnore> <includes> <include>**/*Test.java</include> </includes> <excludes> <!-- --> </excludes> </configuration> </plugin> </plugins>
二、用Maven 运行项目。
mvn surefire-report:report
三、使用maven-antrun-extended-plugin
使用maven-surefire-plugin生成的报告太简陋,可以通过maven-antrun系列插件生成更好的报告。
<!-- 用mvn ant生成格式更友好的report --> <plugin> <groupId>org.jvnet.maven-antrun-extended-plugin</groupId> <artifactId>maven-antrun-extended-plugin</artifactId> <executions> <execution> <id>test-reports</id> <phase>test</phase> <configuration> <tasks> <junitreport todir="${basedir}/target/surefire-reports"> <fileset dir="${basedir}/target/surefire-reports"> <include name="**/*.xml" /> </fileset> <report format="frames" todir="${basedir}/target/surefire-reports" /> </junitreport> </tasks> </configuration> <goals> <goal>run</goal> </goals> </execution> </executions> <dependencies> <dependency> <groupId>org.apache.ant</groupId> <artifactId>ant-junit</artifactId> <version>1.8.0</version> </dependency> <dependency> <groupId>org.apache.ant</groupId> <artifactId>ant-trax</artifactId> <version>1.8.0</version> </dependency> </dependencies> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.1</version> <configuration> <source>1.6</source> <target>1.6</target> <encoding>utf8</encoding> </configuration> </plugin>
用Maven运行后会自动生成单元测试报告,效果如下: