您可以使用 JUnit 类别和 Maven 轻松拆分它们。
下面通过拆分单元测试和集成测试非常非常简要地展示了这一点。
定义一个标记接口
使用类别对测试进行分组的第一步是创建标记界面。
此接口将用于将您要运行的所有测试标记为集成测试。
public interface IntegrationTest {}
标记您的测试课程
将类别注释添加到测试类的顶部。它采用新界面的名称。
import org.junit.experimental.categories.Category;
@Category(IntegrationTest.class)
public class ExampleIntegrationTest{
@Test
public void longRunningServiceTest() throws Exception {
}
}
配置 Maven 单元测试
这个解决方案的美妙之处在于,单元测试方面并没有真正改变。
我们只需向 maven surefire 插件添加一些配置,使其忽略任何集成测试。
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.11</version>
<dependencies>
<dependency>
<groupId>org.apache.maven.surefire</groupId>
<artifactId>surefire-junit47</artifactId>
<version>2.12</version>
</dependency>
</dependencies>
<configuration>
<includes>
<include>**/*.class</include>
</includes>
<excludedGroups>com.test.annotation.type.IntegrationTest</excludedGroups>
</configuration>
</plugin>
当您执行 mvn clean 测试时,只会运行未标记的单元测试。
配置 Maven 集成测试
同样,此配置非常简单。
要仅运行集成测试,请使用以下命令:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.11</version>
<dependencies>
<dependency>
<groupId>org.apache.maven.surefire</groupId>
<artifactId>surefire-junit47</artifactId>
<version>2.12</version>
</dependency>
</dependencies>
<configuration>
<groups>com.test.annotation.type.IntegrationTest</groups>
</configuration>
</plugin>
如果将其包装在 ID 为 IT 的配置文件中,则只能使用 mvn clean install 运行快速测试。要仅运行集成/慢速测试,请使用 mvn clean install -P IT。
但大多数情况下,您会希望默认运行快速测试并使用-P IT 运行所有 测试。如果是这样的话,那你就得用个技巧了:
<profiles>
<profile>
<id>IT</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<excludedGroups>java.io.Serializable</excludedGroups> <!-- An empty element doesn't overwrite, so I'm using an interface here which no one will ever use -->
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
如您所见,我排除了带有java.io.Serializable 注释的测试。这是必要的,因为配置文件将继承 Surefire 插件的默认配置,因此即使您说 <excludedGroups/> 或 <excludedGroups></excludedGroups>,也会使用值 com.test.annotation.type.IntegrationTest。
你也不能使用none,因为它必须是类路径上的一个接口(Maven 会检查这个)。
注意事项:
- 仅当 Maven 不自动切换到 JUnit 4 运行器时,才需要对
surefire-junit47 的依赖。使用groups 或excludedGroups 元素应该会触发切换。 See here。
- 上面的大部分代码取自 Maven Failsafe 插件的文档。请参阅“使用 JUnit 类别”on this page 部分。
- 在我的测试中,我发现当您使用
@RunWith() 注释运行套件或基于 Spring 的测试时,这甚至可以正常工作。