如何在maven surefire运行测试之前执行一次方法

时间:2016-01-20 22:31:11

标签: java maven junit4 maven-surefire-plugin

我有一个测试套件,需要预先执行一些设置代码,以确保我们的数据库中的某些数据是正确的。

我们正在使用maven surefire插件并行运行测试。 ${tests.wildcard}由个人资料指定。

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.16</version>
    <configuration>
        <forkCount>4</forkCount>
        <reuseForks>false</reuseForks>
        <includes>
            <include>${tests.wildcard}</include>
        </includes>
    </configuration>
</plugin>

我希望能够在surefire并行运行我的测试之前,每个整个maven执行一次只运行一次方法。我怎么能这样做?

1 个答案:

答案 0 :(得分:3)

您可以拥有一个执行验证码的特殊测试用例(如果是这样,则会失败)。

此测试用例将由特定的Maven Surefire执行(不包括其他测试)执行,并在test阶段(如process-test-classes)之前附加到Maven阶段occurring:因此,每次Maven运行和任何其他测试之前有效地调用一次。

然后,正常的test阶段将执行任何其他所需的测试,不包括特殊的初始化测试。

这种配置的一个例子是:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.19</version>
    <configuration>
        <excludes>
            <exclude>**/InitTest.java</exclude>
        </excludes>
    </configuration>
    <executions>
        <execution>
            <id>test-init</id>
            <phase>process-test-classes</phase>
            <goals>
                <goal>test</goal>
            </goals>
            <configuration>
                <test>InitTest</test>
            </configuration>
        </execution>
    </executions>
</plugin>

请注意,任何Surefire执行的全局配置都将排除特殊的init测试。然后执行另一个执行(在test阶段之前),并且仅运行init测试(使用<test>元素,其中priority超过任何其他包含/排除。)< / p>

因此,您将拥有以下流程:

  • 执行特殊初始化测试并将数据验证到数据库中(如果需要,则失败)
  • 执行任何其他测试

<强>更新
请注意,您可以通过覆盖默认的surefire测试执行(具有default-test执行ID)来运行特殊测试(并排除其他测试)然后添加另一个surefire执行来实现相同的,并且可能以更加语义正确的方式实现。其余的(如上所述为全局配置,这次是特定的执行配置) 使用这种方法,所有内容都将附加到test阶段,这就是为什么它在语义上更正确,尽管在pom中稍微冗长一点。