I have a Grizzly HttpServer
that I want to run for the entire duration of a test group execution. Additionally, I want to interact with the global HttpServer instance from a @Rule
inside the tests themselves.
Since I'm using Maven Surefire rather than using JUnit test suites, I can't use @BeforeClass
/@AfterClass
on the test suite itself.
Right now, all I can think of is lazily initialising a static field and stopping the server from a Runtime.addShutdownHook()
-- not nice!
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