2013-02-08 57 views
5

我想要在整个测试组执行期间运行灰熊HttpServer。另外,我想在测试本身内部与@Rule中的全局HttpServer实例进行交互。在绝对执行的所有测试之前和之后运行代码

由于我使用Maven Surefire而不是使用JUnit测试套件,因此我无法在测试套件本身上使用@BeforeClass/@AfterClass

现在,我所能想到的只是懒惰地初始化一个静态字段,并停止服务器从Runtime.addShutdownHook() - 不好!

+0

? – TheWhiteRabbit 2013-02-08 11:41:30

+0

如果你正在使用POJO或TestNG测试,你可以使用@BeforeClass – TheWhiteRabbit 2013-02-08 11:45:10

+0

@TechExchange更新的问题,以澄清我使用的Maven surefire – hertzsprung 2013-02-08 11:52:44

回答

7

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

<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-teststoppost-integration-test。我不确定是否有灰熊的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。这些将启动/停止您想要的服务。然后,在万无一失的,你可以指定一个自定义的监听器,使用:

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

这是如果不是的JUnit您使用哪一个Maven Surefire Plugin, Using JUnit, Using custom listeners and reporters

+0

我不认为第一个选项将工作,因为我需要访问'HttpServer'实例从'TestRule',但'RunListener'听起来很有前途,谢谢! – hertzsprung 2013-02-08 13:23:04

+0

对我来说,作为预集成阶段的一部分,jetty服务器启动。最后的日志行是:[INFO]启动Jetty服务器。之后,没有任何反应。它卡住了。 maven surefire failsafe插件不会执行测试,也不会停止jetty服务器。任何想法有什么不对?我使用的是您指定的相同配置。 – 2013-04-26 05:43:03

相关问题