JUnit是单元测试事实上的标准,所以我们这里仅介绍如何在Maven中使用JUnit进行单元测试。
为了实现单元测试,需要引入JUnit的Dependency:
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency>
<build> <pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>${maven-surefire-plugin.version}</version> <configuration> <includes> <include>**/*.java</include> </includes> <excludes> <exclude>**/AppTest.java</exclude> </excludes> </configuration> </plugin> </plugins> </pluginManagement> </build>
配置完成后可以使用如下命令开始进行测试:
mvn test
或者你本次不想进行任何测试,那么可以使用:
<build> <pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>${maven-surefire-plugin.version}</version> <configuration> <skip>true</skip> </configuration> </plugin> </plugins> </pluginManagement> </build>
<build> <pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugin</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>${maven-compiler-plugin.version}</version> <configuration> <skip>true</skip> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>${maven-surefire-plugin.version}</version> <configuration> <skip>true</skip> </configuration> </plugin> </plugins> </pluginManagement> </build>
surefire生成的测试结果位于:target\surefire-reports目录,一个文本形式比较简单,另一个xml格式的详细记录了测试信息。
有时我们期望能拿到覆盖率报告,可以确认是否所有代码都是经测试的,所以我们需要另一个plugin: cobertura:
<plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>cobertura-maven-plugin</artifactId> <version>${cobertura-maven-plugin.version}</version> <configuration> <formats> <format>xml</format> <format>html</format> </formats> </configuration> <executions> <execution> <goals> <goal>clean</goal> <goal>check</goal> </goals> </execution> </executions> </plugin>
运行命令即可查看结果:
mvn cobertura:cobertura结果保存在arget\site\cobertura目录。