有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在surefire执行的所有测试之前和之后运行代码

我有一个Grizzly HttpServer,我想在测试组执行的整个过程中运行它。此外,我想从测试本身内部的@Rule与全局HttpServer实例进行交互

因为我使用的是Maven Surefire,而不是JUnit测试套件,所以我不能在测试套件本身上使用@BeforeClass/@AfterClass

现在,我所能想到的就是懒洋洋地初始化一个静态字段,然后从Runtime.addShutdownHook()停止服务器--这可不好


共 (1) 个答案

  1. # 1 楼答案

    有两种选择,maven解决方案和surefire解决方案。最不耦合的解决方案是在pre-integration-testpost-integration-test阶段执行插件。见Introduction to the Build Lifecycle - Lifecycle Reference。我不熟悉grizzly,但这里有一个使用jetty的示例:

     <build>
      <plugins>
       <plugin>
        <groupId>org.mortbay.jetty</groupId>
        <artifactId>maven-jetty-plugin</artifactId>
        <configuration>
         <contextPath>/xxx</contextPath>
        </configuration>
        <executions>
         <execution>
          <id>start-jetty</id>
          <phase>pre-integration-test</phase>
          <goals>
           <goal>run</goal>
          </goals>
          <configuration>
          </configuration>
         </execution>
         <execution>
          <id>stop-jetty</id>
          <phase>post-integration-test</phase>
          <goals>
           <goal>stop</goal>
          </goals>
         </execution>
        </executions>
       </plugin>
    

    注意start的相位是pre-integration-test,而stop的相位是post-integration-test。我不确定是否有grizzly maven插件,但您可以使用maven-antrun-plugin

    第二个选项是使用JUnit RunListenerRunListener侦听测试事件,例如测试开始、测试结束、测试失败、测试成功等

    public class RunListener {
        public void testRunStarted(Description description) throws Exception {}
        public void testRunFinished(Result result) throws Exception {}
        public void testStarted(Description description) throws Exception {}
        public void testFinished(Description description) throws Exception {}
        public void testFailure(Failure failure) throws Exception {}
        public void testAssumptionFailure(Failure failure) {}
        public void testIgnored(Description description) throws Exception {}
    }
    

    所以你可以听RunStarted和RunFinished。这些将启动/停止您想要的服务。然后,在surefire中,可以使用以下命令指定自定义侦听器:

    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-surefire-plugin</artifactId>
      <version>2.10</version>
      <configuration>
        <properties>
          <property>
            <name>listener</name>
            <value>com.mycompany.MyResultListener,com.mycompany.MyResultListener2</value>
          </property>
        </properties>
      </configuration>
    </plugin>
    

    这是来自Maven Surefire Plugin, Using JUnit, Using custom listeners and reporters