我继承了 Junit 测试的负载,但这些测试(除了大多数不工作之外)是实际单元测试和集成测试(需要外部系统、数据库等)的混合体。
所以我正在尝试想出一种方法将它们真正分开,这样我就可以很好、快速地运行单元测试,然后进行集成测试。
选项是..
将它们分成不同的目录。
移至 Junit4(来自 v3)并注释类以将它们分开。
使用文件命名约定来说明类是什么,即 AdapterATest 和 AdapterAIntergrationTest.
3 的问题是 Eclipse 可以选择“在选定的项目/包或文件夹中运行所有测试”。因此,仅运行集成测试会变得非常困难。
2:开发人员可能会开始在单元测试类中编写集成测试,结果会变得一团糟。
1:这似乎是最简洁的解决方案,但我的直觉告诉我必须有更好的解决方案。
所以这就是我的问题,你们如何拆分集成测试和适当的单元测试?
最佳答案
您可以使用 JUnit 类别和 Maven 非常轻松地拆分它们。
下面通过拆分单元测试和集成测试非常非常简要地展示了这一点。
定义标记接口(interface)
使用类别对测试进行分组的第一步是创建标记界面。此接口(interface)将用于标记您希望作为集成测试运行的所有测试。
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
因为它必须是类路径上的接口(interface)(Maven 会检查它)。
注意事项:
- 对
surefire-junit47
的依赖仅当 Maven 未自动切换到 JUnit 4 运行程序时才需要。使用groups
或excludedGroups
元素应该触发开关。 See here . - 上面的大部分代码取自 Maven Failsafe 插件的文档。请参阅“使用 JUnit 类别”部分 on this page .
- 在我的测试中,我发现这甚至在你使用
@RunWith()
时也有效。用于运行套件或基于 Spring 的测试的注释。
关于unit-testing - Junit:拆分集成测试和单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2606572/