Running code before and after all tests in a surefire execution

喜欢而已 提交于 2019-12-05 09:10:54
Matthew Farwell

There are two options, a maven solution and a surefire solution. The least coupled solution is to execute a plugin in the pre-integration-test and post-integration-test phase. See Introduction to the Build Lifecycle - Lifecycle Reference. I'm not familiar with grizzly, but here is an example using 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>

Note that the phase for start is pre-integration-test and stop is post-integration-test. I'm not sure if there is a grizzly maven plugin, but you could use the maven-antrun-plugin instead.

The second option is to use a JUnit RunListener. RunListener listens to test events, such as test start, test end, test failure, test success etc.

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 {}
}

So you could listen for RunStarted and RunFinished. These would start/stop the services you want. Then, in surefire, you can specify a custom listener, using:

<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>

This is from Maven Surefire Plugin, Using JUnit, Using custom listeners and reporters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!