您可以使用 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/>
or ,也会使用<excludedGroups></excludedGroups>
该值。com.test.annotation.type.IntegrationTest
您也不能使用none
,因为它必须是类路径上的接口(Maven 将检查这一点)。
笔记:
surefire-junit47
仅当 Maven 不自动切换到 JUnit 4 运行器时,才需要依赖 to 。使用groups
orexcludedGroups
元素应该触发开关。见这里。
- 上面的大部分代码都取自 Maven Failsafe 插件的文档。请参阅此页面上的“使用 JUnit 类别”部分。
- 在我的测试中,我发现当你使用
@RunWith()
注解来运行套件或基于 Spring 的测试时,这甚至可以工作。