【问题标题】:How to execute a method once before maven surefire runs tests如何在 maven surefire 运行测试之前执行一次方法
【发布时间】:2016-04-26 23:58:18
【问题描述】:

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

我们正在使用 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 执行中只运行一次方法。我该怎么做?

【问题讨论】:

  • 您是否查看了this 和this 的答案以获得一些提示?
  • 是的,不过这些都行不通。这将使我的代码在每个类中运行一次,而不是在每个 maven 执行中运行一次。

标签: java maven junit4 maven-surefire-plugin


【解决方案1】:

您可以有一个特殊的测试用例来执行您的验证码(如果是这种情况则失败)。

然后,这个测试用例将由特定的 Maven Surefire 执行(不包括其他测试)执行,并在 test 阶段之前附加到 Maven 阶段 occurring(如 process-test-classes):因此,有效地被调用一次每次 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 执行的全局配置都会排除特殊的初始化测试。然后将执行额外的执行(在test 阶段之前),并且将仅运行初始化测试(使用&lt;test&gt; 元素,它将priority 置于任何其他包含/排除之上)。

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

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

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

【讨论】:

  • @Andy 你试过这种方法吗?有什么反馈吗?
  • 抱歉,还没有机会查看这个。当我这样做时,我一定会回复和/或接受您的回答。感谢您的建议!
猜你喜欢
  • 2014-02-11
  • 1970-01-01
  • 2011-04-05
  • 1970-01-01
  • 1970-01-01
  • 2020-05-20
  • 2023-03-09
  • 2020-12-31
  • 2021-05-16
相关资源
最近更新 更多